Chapter 23: Operators
1. What is an Operator?
An operator is a special symbol (or sometimes a word) that tells Swift to perform an action on one or more values.
Examples you already know:
|
0 1 2 3 4 5 6 7 8 9 |
10 + 5 // + is an operator age >= 18 // >= is an operator name == "Priya" // == is an operator !isLoggedIn // ! is an operator |
Swift has many categories of operators. We will look at the most important ones in detail — the ones you will use almost every day.
2. Arithmetic Operators — + – * / %
These work with numbers (Int, Double, Float, Decimal, etc.).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let a = 20 let b = 7 print(a + b) // 27 print(a - b) // 13 print(a * b) // 140 print(a / b) // 2 ← integer division → drops the decimal part print(a % b) // 6 ← remainder (modulo) |
Important behavior with floating-point numbers:
|
0 1 2 3 4 5 6 7 8 9 10 |
let x = 20.0 let y = 7.0 print(x / y) // 2.857142857142857 ← keeps decimals print(x.truncatingRemainder(dividingBy: y)) // 6.0 |
Compound assignment — very common shorthand
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var score = 150 score += 50 // score = score + 50 → 200 score -= 30 // → 170 score *= 2 // → 340 score /= 4 // → 85 score %= 7 // → 1 (remainder) print(score) // 1 |
Realistic example – shopping cart
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let itemPrice: Decimal = 899.99 let quantity = 2 let discountPercent: Decimal = 15 var total = itemPrice * Decimal(quantity) // 1799.98 total -= total * (discountPercent / 100) // subtract discount total += total * 0.18 // add 18% GST print("Final amount: ₹\(total)") // Final amount: ₹1897.9784 |
3. Comparison Operators — == != > < >= <=
These always return a Bool (true or false).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let temperature = 36.8 print(temperature == 37.0) // false print(temperature != 37.0) // true print(temperature > 37.5) // false print(temperature >= 36.6) // true print(temperature < 35.0) // false print(temperature <= 38.0) // true |
Very frequent beginner mistake:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let username = "Rahul" // Wrong (case-sensitive): if username == "rahul" { … } // false! // Better: if username.lowercased() == "rahul" { … } |
Another common pattern:
|
0 1 2 3 4 5 6 7 8 9 |
let password = "secret123" let minLength = 8 let isStrongEnough = password.count >= minLength && password != "password123" |
4. Logical Operators — && || !
| Operator | Name | Meaning | Example | Result when |
|---|---|---|---|---|
| && | Logical AND | Both must be true | age >= 18 && hasLicense | true only if both true |
|
Logical OR | At least one must be true | ||
| ! | Logical NOT | Reverse the value | !isLoggedIn | true → false, false → true |
Real example – access control
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let age = 20 let hasLicense = true let hasInsurance = false let canRentCar = age >= 18 && hasLicense && hasInsurance print(canRentCar) // false (because insurance missing) |
Short-circuit evaluation (very important concept)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let user: User? = nil // Safe — right side is NOT evaluated if left is false if user != nil && user!.isPremium { print("Show premium badge") } |
5. Nil-Coalescing Operator — ??
Very common when dealing with optionals.
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let nickname: String? = nil let displayName = nickname ?? "Anonymous" print(displayName) // Anonymous let points: Int? = nil let score = points ?? 0 |
Real-life usage – profile screen
|
0 1 2 3 4 5 6 7 |
let bio: String? = nil let displayBio = bio ?? "No bio available yet" |
6. Ternary Conditional Operator — ? :
Short version of if-else.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let age = 16 let status = age >= 18 ? "Adult" : "Minor" print(status) // Minor // Real example – button text let buttonText = isLoggedIn ? "Sign Out" : "Sign In" |
More readable with multiple conditions
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let temp = 38.2 let message = temp < 35 ? "Too cold 🥶" : temp > 38 ? "Fever 😷" : "Normal 🌡️" print(message) // Fever 😷 |
7. Range Operators — … ..<
Very common in loops, switches, array slices.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Closed range (includes both ends) for i in 1...5 { // 1, 2, 3, 4, 5 print(i) } // Half-open range (up to, but not including) for i in 0..<10 { // 0, 1, 2, ..., 9 print(i) } // One-sided ranges let scores = [78, 85, 92, 65, 88] let topThree = scores[..<3] // [78, 85, 92] let fromSecond = scores[1...] // [85, 92, 65, 88] |
Very common in switch statements
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let marks = 87 switch marks { case 90...100: print("Outstanding 🎉") case 75..<90: print("Very good 👍") case 60..<75: print("Good") default: print("Needs improvement") } |
8. Quick Summary Table – Most Used Operators
| Category | Operators | Example | Typical Use Case |
|---|---|---|---|
| Arithmetic | + – * / % | price * quantity | Calculations |
| Compound assignment | += -= *= /= %= | total += tax | Updating variables |
| Comparison | == != > < >= <= | age >= 18 | Conditions |
| Logical | && |
! | |
| Nil-coalescing | ?? | name ?? “Guest” | Safe optional defaults |
| Ternary | ?: | isDarkMode ? “Dark” : “Light” | Short if-else |
| Range | … ..< | 1…10, 0..<array.count | Loops, switches, array slices |
| Identity (classes) | === !== | objectA === objectB | Check same instance |
9. Small Practice – Combine Operators
Try writing these:
- Calculate final price: base = 999.99 + 18% tax
- Check if user can enter: age ≥ 18 AND has ticket AND NOT banned
- Set greeting: “Welcome back” if logged in, else “Hello guest”
Would you like to go deeper into any group?
- Arithmetic & money calculations in detail
- Logical operators in complex real conditions
- Ranges + switch + array slicing
- Ternary vs if-else – when to choose which
- Or move to next topic (control flow, functions, optionals…)
Just tell me — we’ll continue in the same slow, clear, teacher-like way 😊
