Chapter 45: Swift if
1. What does if actually do?
if is the most basic decision-making tool in programming.
It lets your code ask a yes/no question and then choose what to do based on the answer.
The condition inside if must be something that results in true or false (a Bool value).
Basic form:
|
0 1 2 3 4 5 6 7 8 |
if condition { // This code runs only when condition is true } |
Very simple first example:
|
0 1 2 3 4 5 6 7 8 9 10 |
let temperature = 33 if temperature > 30 { print("It's hot today 🥵") } |
If you run this code when temperature is 33 → you see the message. If you change it to 25 → nothing happens (because condition is false).
2. Adding else — what to do when condition is false
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let temperature = 28 if temperature > 30 { print("It's hot 🥵 – drink water!") } else { print("Nice weather 😊 – good for a walk") } |
Now the code always does something — either the hot message or the nice weather message.
3. else if — checking several possibilities
When you have more than two possible situations, you use else if.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let temperature = 26 if temperature > 38 { print("Extreme heat warning! Stay indoors 🏠💧") } else if temperature > 32 { print("Very hot – lots of water and shade please 🥤") } else if temperature > 27 { print("Warm and pleasant day 😎") } else if temperature > 18 { print("Cool weather – light jacket 🧥") } else { print("It's cold outside ❄️ – wear something warm") } |
Important rules about else if chains:
- Swift checks conditions from top to bottom
- As soon as one condition is true, it runs that block and skips all the following ones
- Order is very important — put the most specific / highest value conditions first
- The final else (optional) catches everything that didn’t match above
Classic mistake example (very common for beginners):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let score = 92 if score >= 80 { print("A") // ← this runs → prints "A" } else if score >= 90 { print("A+") // ← never reached! } |
Correct version:
|
0 1 2 3 4 5 6 7 8 9 10 |
if score >= 90 { print("A+") } else if score >= 80 { print("A") } |
4. Real-life examples — the kind of code you will write every day
Example 1 – User login status
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let isLoggedIn = true let hasPremium = false if isLoggedIn { if hasPremium { print("Welcome back, Premium member! 🎖️ Enjoy all features.") } else { print("Welcome back! Consider upgrading to Premium ✨") } } else { print("Please sign in to continue") } |
Example 2 – Basic age check (very common)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let age = 17 if age >= 18 { print("You can vote ✓") print("You can buy lottery tickets") } else if age >= 16 { print("You can get a learner's driving license") } else { print("You're still young — enjoy school! 🎒") } |
Example 3 – Weather advice (classic beginner-to-intermediate exercise)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
let temperature = 34.5 let isRaining = false var advice = "" if temperature > 38 { advice = "Dangerous heat! Stay indoors and drink water 🏠💧" } else if temperature > 32 { advice = "Very hot day – avoid direct sun 🥵" } else if temperature > 25 { advice = "Warm and pleasant – light clothes are fine 😎" } else if temperature > 15 { advice = "Cool weather – a jacket might be good 🧥" } else { advice = "It's cold outside – wear warm layers ❄️" } if isRaining { advice += "\nDon't forget an umbrella ☔" } print("Weather advice for today:") print(advice) |
Example 4 – Mini grade calculator
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
let percentage = 82.5 let grade: String if percentage >= 90 { grade = "A+" } else if percentage >= 80 { grade = "A" } else if percentage >= 70 { grade = "B" } else if percentage >= 60 { grade = "C" } else if percentage >= 50 { grade = "D" } else { grade = "F" } print("You scored \(percentage)% → Grade: \(grade)") |
5. Important Details & Best Practices
Detail 1 – Condition must be Bool
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let age = 20 // Correct if age >= 18 { … } // Wrong if age { … } // ❌ Compile error – Int is not Bool |
Detail 2 – Prefer positive conditions when possible
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Harder to read if !isLoggedIn { showLogin() } // Easier to read if isLoggedIn { showDashboard() } else { showLogin() } |
Detail 3 – Use guard for early exit (very modern & recommended)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
func greetUser(user: User?) { guard let user else { print("No user provided") return } guard user.age >= 18 else { print("User is underage") return } // happy path – user exists and is adult print("Welcome, \(user.name)!") } |
guard makes code flatter and much easier to read than deep nesting.
6. Very Common Beginner Mistakes & How to Fix Them
| Mistake | Wrong code | Correct / Better way | Why? |
|---|---|---|---|
| Using = instead of == | if age = 18 { … } | if age == 18 { … } | = is assignment – compile error here |
| Writing == true / == false everywhere | if isAdult == true { … } | if isAdult { … } | Cleaner, more idiomatic |
| Wrong order in else-if chain | else if score >= 90 { “A+” } before >=80 | Put highest condition first | First true condition wins |
| Deep nesting instead of guard | many nested ifs | Use guard + early return | Flatter, easier to read code |
| Comparing optionals directly | if optional == 10 { … } | if let value = optional, value == 10 { … } | optional == 10 usually means you forgot nil |
7. Quick Reference – if patterns you will use most
| Situation | Recommended pattern | Example |
|---|---|---|
| Simple yes/no | if condition { … } else { … } | if isRaining { takeUmbrella() } else { walk() } |
| Multiple ranges / categories | if … else if … else if … else { … } | temperature, grade, score ranges |
| Early exit / validation | guard condition else { return / throw / … } | guard let user else { return } |
| Optional unwrapping + condition | if let value = optional, value > 10 { … } | Safe optional handling |
| Short one-liner | if condition { doSomething() } | if isLoading { showSpinner() } |
8. Small Practice – Try these
- Write weather advice code:
-
38 → “Extreme heat! Stay inside”
- 32–38 → “Very hot – drink water”
- 25–32 → “Warm day”
- 15–25 → “Pleasant”
- else → “Cold”
-
- Simple login check:
- not logged in → “Please sign in”
- logged in, not premium → “Welcome! Get Premium?”
- logged in + premium → “Welcome Premium member!”
- Mini grade calculator:
- ≥ 90 → “A+”
- 80–89 → “A”
- 70–79 → “B”
- 60–69 → “C”
- below 60 → “Fail”
Paste your code here if you want feedback or want to see cleaner/more modern versions!
What would you like to explore next?
- guard statement in depth (very important companion to if)
- switch statement (often cleaner than long if…else if chains)
- if combined with optionals (if let, if case let, etc.)
- Conditional logic in SwiftUI (showing/hiding views)
- Or move to another topic (loops, functions, arrays, optionals…)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
