Chapter 22: Swift Operators
1. What are Operators?
Operators are special symbols (or sometimes words) that perform an operation on one, two, or three values.
|
0 1 2 3 4 5 6 7 8 9 |
let a = 10 + 5 // + is an operator let isAdult = age >= 18 // >= is an operator let name = first + " " + last // + for strings let isEven = number % 2 == 0 // %, == are operators |
Swift has several categories of operators. We’ll look at the most important ones in detail.
2. Arithmetic Operators (+ – * / %)
These work with numbers (Int, Double, Float, Decimal).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let a = 10 let b = 3 print(a + b) // 13 print(a - b) // 7 print(a * b) // 30 print(a / b) // 3 (integer division → drops decimal part) print(a % b) // 1 (remainder) // With floating point let x = 10.0 let y = 3.0 print(x / y) // 3.3333333333333335 print(x.truncatingRemainder(dividingBy: y)) // 1.0 |
Compound assignment operators (very common)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
var score = 100 score += 50 // same as score = score + 50 score -= 20 score *= 2 score /= 4 score %= 7 print(score) // 60 |
Real-life example – price calculation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let itemPrice: Decimal = 1499.99 let quantity = 3 let taxRate: Decimal = 0.18 var subtotal = itemPrice * Decimal(quantity) subtotal += subtotal * taxRate // add tax print("Total: ₹\(subtotal)") // Total: ₹5311.9702 |
3. Comparison Operators (== != > < >= <=)
Return Bool (true or false)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let age = 19 print(age == 18) // false print(age != 18) // true print(age > 18) // true print(age >= 18) // true print(age < 16) // false print(age <= 21) // true |
Very common mistake beginners make:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let name = "Rahul" // Wrong: if name == "rahul" { … } // false – case sensitive! // Better: if name.lowercased() == "rahul" { … } |
4. Logical Operators (&& || !)
Combine or invert Bool values
| Operator | Name | Meaning | Example | Result |
|---|---|---|---|---|
| && | AND | Both must be true | age >= 18 && hasLicense | true only if both true |
|
OR | At least one must be true | ||
| ! | NOT | Reverses the value | !isLoggedIn | true → false, false → true |
Real example – form validation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let email = "aarav@example.com" let password = "Secure123!" let emailValid = email.contains("@") && email.contains(".") let passwordLong = password.count >= 8 let passwordsMatch = true // assume confirmed let canSubmit = emailValid && passwordLong && passwordsMatch print(canSubmit) // true |
Short-circuit evaluation (very important to understand)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let user: User? = nil // This is safe – right side not evaluated if left is false if user != nil && user!.isPremium { print("Show premium badge") } |
5. Assignment Operator (=)
|
0 1 2 3 4 5 6 7 8 |
var score = 0 score = 100 score = score + 50 |
Compound versions (already seen):
|
0 1 2 3 4 5 6 7 8 9 10 |
score += 50 score -= 20 score *= 2 score /= 5 score %= 7 |
6. Ternary Conditional Operator (?:) – very popular
Short version of if-else
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let age = 19 let status = age >= 18 ? "Adult" : "Minor" print(status) // Adult // Real example let buttonTitle = isLoggedIn ? "Logout" : "Login" |
More readable version with multiple conditions
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let temperature = 36.8 let message = temperature < 35 ? "Too cold ❄️" : temperature > 38 ? "Fever 😷" : "Normal 👍" print(message) |
7. 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 ?? "Guest" print(displayName) // Guest let score: Int? = nil let points = score ?? 0 |
Real usage – user profile
|
0 1 2 3 4 5 6 7 |
let userBio: String? = nil let bioText = userBio ?? "No bio yet" |
8. Range Operators
Very common in loops and switches
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// 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 end for i in 0..<10 { // 0 to 9 print(i) } // One-sided ranges (Swift 4+) let numbers = [10, 20, 30, 40, 50] let firstThree = numbers[..<3] // [10, 20, 30] let fromThird = numbers[2...] // [30, 40, 50] |
9. Identity Operators (=== !==) – only for classes
These check whether two references point to the same instance (not value equality)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Person { var name: String init(name: String) { self.name = name } } let p1 = Person(name: "Rahul") let p2 = Person(name: "Rahul") let p3 = p1 print(p1 === p2) // false – different objects print(p1 === p3) // true – same object |
10. Quick Reference Table – Most Used Operators
| Category | Operator(s) | Example | Result / Use Case |
|---|---|---|---|
| Arithmetic | + – * / % | price * quantity | Calculations |
| Compound assignment | += -= *= /= %= | score += 100 | Updating variables |
| Comparison | == != > < >= <= | age >= 18 | Conditions |
| Logical | && |
! | |
| Ternary | ?: | isLoggedIn ? “Logout” : “Login” | Short if-else |
| Nil-coalescing | ?? | name ?? “Anonymous” | Safe optional unwrapping |
| Range | … ..< | 1…10, 0..<count | Loops, switches, slices |
| Identity | === !== | object1 === object2 | Check same instance (classes only) |
11. Small Practice – Combine Operators
Try to write these using operators:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// 1. Calculate final price with 18% tax let basePrice = 999.99 let taxRate = 0.18 // your code here // 2. Check if user can vote (age 18+ and Indian citizen) let age = 19 let isIndian = true // your code here // 3. Show "Welcome back" if logged in, otherwise "Sign in" let isLoggedIn = true // your code here |
Would you like to go deeper into any specific operator group?
- Arithmetic & compound assignment in real calculations
- Logical operators in complex conditions
- Ternary & nil-coalescing patterns
- Ranges in SwiftUI / loops / switch
- Or move to another topic (control flow, functions, optionals…)
Just tell me — we’ll continue in the same detailed, clear, teacher-like style 😊
