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
- Arithmetic operators: addition, subtraction, multiplication, division, remainder
- Assignment operators and compound assignment
- Comparison operators and Boolean results
- Logical operators: AND, OR, NOT
- The ternary operator and numeric type conversion
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:
let currentRevenue = 250_000
let previousRevenue = 200_000
let growthRate = (currentRevenue - previousRevenue) / previousRevenue * 100
print("Growth rate: \(growthRate)%")
Output:
TEXT 📖 Display onlyGrowth 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:
let currentRevenue = 250_000.0
let previousRevenue = 200_000.0
let growthRate = (currentRevenue - previousRevenue) / previousRevenue * 100
print("Growth rate: \(growthRate)%")
Output:
TEXT 📖 Display onlyGrowth 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.
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
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)
(2) Compound Assignment Operators
Compound assignment operators combine arithmetic with assignment in a more concise form:
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
// ============================================
// 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 onlyMonthly 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.
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
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 |
let hasTicket = true
let isVip = false
let canEnter = hasTicket && isVip // false
let canAccess = hasTicket || isVip // true
let isNotVip = !isVip // true
▶ Example: User Permission Check
// ============================================
// 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 onlyAdult: 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:
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 |
var result: String
if score >= 60 {
result = "Pass"
} else {
result = "Fail"
}
let result2 = score >= 60 ? "Pass" : "Fail"
(2) Numeric Type Conversion
Int and Double require explicit conversion between them:
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
// ============================================
// 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 onlyPurchase 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
// ============================================
// 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
Double(10) / 3 gives 3.3333. Or declare it as 10.0 / 3 from the start.truncatingRemainder(dividingBy:) method.&& 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.x += 5 is a statement, not an expression, and cannot be used in assignments or comparisons. This differs from C.📖 Summary
- Arithmetic operators:
+-*/%. Int division truncates decimals. - Compound assignment:
+=-=*=/=for concise variable updates. - Comparison operators:
==!=><>=<=. All return Bool. - Logical operators:
&&(AND),||(OR),!(NOT). Support short-circuit evaluation. - Ternary operator:
condition ? valueA : valueBfor one-line either-or choices. - Numeric type conversion:
Double()orInt()to ensure type compatibility.
📝 Exercises
- Beginner: Use arithmetic operators to calculate the area and perimeter of a rectangle with length 12.5 and width 8.3. Output the results.
- 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.
- 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.