Swift: Swift Operators

Operators are the calculation symbols in your code. This lesson covers all basic operators in Swift and how to use them effectively.

1. What You'll Learn


2. A True Story: A Financial Analyst

(1) The Pain Point: Int Division Lost Decimals, Breaking a Report

Bob is a financial analyst at a startup who needed to calculate quarterly revenue growth. He wrote this code:

SWIFT
let currentRevenue = 250_000
let previousRevenue = 200_000
let growthRate = (currentRevenue - previousRevenue) / previousRevenue * 100
print("Growth rate: \(growthRate)%")

Output:

TEXT 📖 Display only
Growth rate: 0%

Bob knew the actual growth rate should be 25%, but the code output 0%. The reason: Int division truncates decimals—50,000 / 200,000 equals 0 in integer arithmetic, and multiplying by 100 still gives 0.

(2) The Solution: Using Double for Accurate Calculations

Switching the data to Double preserves decimals during division:

SWIFT
let currentRevenue = 250_000.0
let previousRevenue = 200_000.0
let growthRate = (currentRevenue - previousRevenue) / previousRevenue * 100
print("Growth rate: \(growthRate)%")

Output:

TEXT 📖 Display only
Growth rate: 25.0%

Problem solved instantly. Bob then audited 12 months of reports and found 4 more instances of precision loss from Int division.

(3) The Result: Report Accuracy After Using the Right Operators

Dimension Before After
Numerical errors 3-5 per month 0
Report review time 2 hours each 15 minutes
Team trust "The report might be wrong" "The data is reliable"
Operator understanding Unclear about Int division behavior Proactively chooses the correct type

3. Arithmetic and Assignment Operators

Arithmetic operators perform mathematical calculations; assignment operators store values in variables. They are the most frequently used operators in Swift.

100%
graph LR
    A[Operators] --> B["Arithmetic: + - * / %"]
    A --> C["Assignment: = += -= *= /="]
    B --> D[Numeric Calculations]
    C --> E[Update Variable Values]
Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3 (Int truncates)
% Remainder 10 % 3 1

(1) Arithmetic Operators

SWIFT
let a = 15
let b = 4
let sum = a + b      // 19
let diff = a - b     // 11
let prod = a * b     // 60
let quot = a / b     // 3 (Int division truncates decimals)
let rem = a % b      // 3 (15 / 4 = 3 remainder 3)
⚠️ Note: Int division directly truncates the decimal part without rounding. 15 / 4 gives 3, not 3.75. Use Double when you need decimal results.

(2) Compound Assignment Operators

Compound assignment operators combine arithmetic with assignment in a more concise form:

SWIFT
var score = 10
score += 5     // Equivalent to score = score + 5 -> 15
score -= 3     // Equivalent to score = score - 3 -> 12
score *= 2     // Equivalent to score = score * 2 -> 24
score /= 4     // Equivalent to score = score / 4 -> 6
Compound Operator Meaning Example Equivalent
+= Add and assign x += 5 x = x + 5
-= Subtract and assign x -= 3 x = x - 3
*= Multiply and assign x *= 2 x = x * 2
/= Divide and assign x /= 4 x = x / 4

▶ Example: Monthly Expense Tracker

SWIFT
// ============================================
// Track monthly expense totals
// Demonstrates arithmetic and compound assignment operators
// ============================================
var monthlyExpenses = 0.0
let rent = 1200.00
let groceries = 450.50
let transportation = 85.00
let entertainment = 200.00
monthlyExpenses += rent
monthlyExpenses += groceries
monthlyExpenses += transportation
monthlyExpenses += entertainment
let annualExpenses = monthlyExpenses * 12
let weeklyAverage = monthlyExpenses / 4.33
print("Monthly total: $\(monthlyExpenses)")
print("Annual total: $\(annualExpenses)")
print("Weekly average: $\(String(format: "%.2f", weeklyAverage))")

Output:

TEXT 📖 Display only
Monthly total: $1935.5
Annual total: $23226.0
Weekly average: $447.23

4. Comparison and Logical Operators

Comparison operators compare two values and return a Bool result; logical operators combine multiple Boolean conditions.

100%
graph TB
    A[Comparison Operators] --> B["== Equal to"]
    A --> C["!= Not equal to"]
    A --> D["> Greater than"]
    A --> E["< Less than"]
    A --> F[">= Greater than or equal"]
    A --> G["<= Less than or equal"]
    B --> H[Returns Bool]
    C --> H
    D --> H
Operator Name Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal 5 >= 5 true
<= Less than or equal 5 <= 3 false

(1) Comparison Operators

SWIFT
let age = 18
let isAdult = age >= 18     // true
let canDrive = age >= 16    // true
let isSenior = age > 65     // false
let userName = "Alice"
let isAdmin = userName == "Admin"  // false

(2) Logical Operators

Operator Name Meaning Example
&& AND Both conditions must be true age >= 18 && hasLicense
` ` OR
! NOT Negates the value !isLoggedIn
SWIFT
let hasTicket = true
let isVip = false
let canEnter = hasTicket && isVip   // false
let canAccess = hasTicket || isVip  // true
let isNotVip = !isVip               // true

▶ Example: User Permission Check

SWIFT
// ============================================
// Check if a user has access to the admin panel
// Demonstrates comparison and logical operators
// ============================================
let userAge = 22
let hasVerifiedEmail = true
let isBanned = false
let isAdmin = false
let isAdult = userAge >= 18
let canAccessSystem = isAdult && hasVerifiedEmail && !isBanned
let hasAdminAccess = isAdmin
let finalAccess = canAccessSystem || hasAdminAccess
print("Adult: \(isAdult)")
print("Email verified: \(hasVerifiedEmail)")
print("Not banned: \(!isBanned)")
print("Final access: \(finalAccess)")

Output:

TEXT 📖 Display only
Adult: true
Email verified: true
Not banned: true
Final access: true

5. The Ternary Operator and Type Conversion

The ternary operator is a concise alternative to if-else; numeric type conversion allows different types to work together.

(1) The Ternary Conditional Operator

Syntax: condition ? valueA : valueB — returns valueA if the condition is true, otherwise returns valueB:

SWIFT
let score = 85
let grade = score >= 60 ? "Pass" : "Fail"
print(grade)  // Pass
Style Lines of Code Readability
if-else version 5 lines Clear but verbose
Ternary version 1 line Concise, best for simple conditions
SWIFT
var result: String
if score >= 60 {
    result = "Pass"
} else {
    result = "Fail"
}
let result2 = score >= 60 ? "Pass" : "Fail"
⚠️ Note: The ternary operator works best for simple either-or choices. When conditions get complex, use if-else.

(2) Numeric Type Conversion

Int and Double require explicit conversion between them:

SWIFT
let x = 10       // Int
let y = 3.5      // Double
let result1 = Double(x) + y  // 13.5
let result2 = x + Int(y)     // 13 (y truncated to 3)
Conversion Syntax Result
Int to Double Double(intVal) Keeps integer part, adds .0
Double to Int Int(doubleVal) Truncates decimals, no rounding
Int to String String(intVal) Converts to text

▶ Example: Discount Calculator

SWIFT
// ============================================
// Calculate discount based on purchase amount
// Demonstrates the ternary operator and type conversion
// ============================================
let purchaseAmount = 120.0
let itemCount = 3
let discountRate: Double = purchaseAmount >= 100 ? 0.9 : 1.0
let finalAmount = purchaseAmount * discountRate
let averagePrice = finalAmount / Double(itemCount)
print("Purchase amount: $\(purchaseAmount)")
print("Discount: \(Int((1 - discountRate) * 100))%")
print("Final amount: $\(finalAmount)")
print("Item count: \(itemCount)")
print("Average price per item: $\(String(format: "%.2f", averagePrice))")
let freeShipping = finalAmount >= 100 ? "Free Shipping" : "Shipping Fee"
print("Shipping: \(freeShipping)")

Output:

TEXT 📖 Display only
Purchase amount: $120.0
Discount: 10%
Final amount: $108.0
Item count: 3
Average price per item: $36.00
Shipping: Free Shipping

6. Full Example: Monthly Budget Analyzer

SWIFT
// ============================================
// Monthly budget analysis tool
// Demonstrates arithmetic, comparison, logical, and ternary operators
// ============================================
import Foundation
// 1. Income and expense data
let salary = 5200.0
let rent = 1400.0
let food = 600.0
let transport = 120.0
let utilities = 200.0
let entertainment = 300.0
// 2. Calculate using arithmetic and compound assignment
var totalExpenses = 0.0
totalExpenses += rent
totalExpenses += food
totalExpenses += transport
totalExpenses += utilities
totalExpenses += entertainment
let savings = salary - totalExpenses
let savingsRate = savings / salary * 100
// 3. Use comparison and ternary to assess financial health
let isHealthy = savingsRate >= 20
let advice = isHealthy ? "Healthy" : "Needs Improvement"
// 4. Logical check: any single category over budget?
let rentTooHigh = rent > salary * 0.3
let foodTooHigh = food > salary * 0.15
let needsAdjustment = rentTooHigh || foodTooHigh
print("=== Monthly Budget ===")
print("Income: $\(salary)")
print("Expenses: $\(totalExpenses)")
print("Savings: $\(String(format: "%.2f", savings))")
print("Savings Rate: \(Int(savingsRate))%")
print("Status: \(advice)")
print("Needs Adjustment: \(needsAdjustment)")
// 5. Type conversion example
let categoryCount = 5
let avgPerCategory = totalExpenses / Double(categoryCount)
print("Categories: \(categoryCount), Avg: $\(String(format: "%.2f", avgPerCategory))")

Output:

TEXT 📖 Display only
=== Monthly Budget ===
Income: $5200.0
Expenses: $2620.0
Savings: $2580.0
Savings Rate: 49%
Status: Healthy
Needs Adjustment: false
Categories: 5, Avg: $524.00

❓ FAQ

Q How do I get decimal results from Int division?
A Convert at least one operand to Double. For example, Double(10) / 3 gives 3.3333. Or declare it as 10.0 / 3 from the start.
Q Can the % operator be used with Double?
A No. Swift's % only works with integers. For floating-point remainder, use the truncatingRemainder(dividingBy:) method.
Q Do && and || use short-circuit evaluation?
A Yes. && won't evaluate the right side if the left is false; || won't evaluate the right side if the left is true. Use this wisely to improve efficiency.
Q Do compound assignment operators return a value?
A No. x += 5 is a statement, not an expression, and cannot be used in assignments or comparisons. This differs from C.

📖 Summary


📝 Exercises

  1. Beginner: Use arithmetic operators to calculate the area and perimeter of a rectangle with length 12.5 and width 8.3. Output the results.
  2. Intermediate: Write a program to determine if a year is a leap year. Rule: divisible by 4 but not by 100, or divisible by 400. Use logical operators to combine the conditions.
  3. Challenge: Write an electricity bill calculator. The base rate is $0.12/kWh. For monthly usage exceeding 300kWh, the excess is charged at $0.15/kWh. Use the ternary operator and arithmetic operators to calculate the total bill.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏