Chapter 47: Swift else if
1. What does else if actually do?
else if lets you check multiple different conditions in sequence.
It means:
- First check the if condition
- If that is false → check the first else if
- If that is false → check the next else if
- …and so on
- If none of them are true → run the final else (if you wrote one)
Very important rule:
Swift stops at the first true condition it finds It never checks the conditions that come after
This is why order matters a lot.
2. Basic pattern – the skeleton you will see everywhere
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if firstCondition { // do something } else if secondCondition { // do something else } else if thirdCondition { // do another thing } else { // none of the above were true } |
The last else is optional — you can leave it out.
3. Very first examples – feel how it works
Example 1 – Temperature advice
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let temperature = 29 if temperature > 38 { print("Dangerous heat! Stay indoors 🏠💧") } else if temperature > 32 { print("Very hot day – lots of water 🥤") } else if temperature > 26 { print("Warm and sunny – light clothes 😎") } else if temperature > 18 { print("Pleasant weather – enjoy the day 🌤️") } else { print("It's cold – wear something warm ❄️") } |
What happens when temperature = 29?
-
38? No
-
32? No
-
26? Yes → prints “Warm and sunny – light clothes 😎”
- stops — never checks the rest
Example 2 – No final else
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let score = 85 if score >= 90 { print("A+") } else if score >= 80 { print("A") } else if score >= 70 { print("B") } // no else → if score < 70 nothing is printed |
This pattern is very common when you only want to react to certain good cases and ignore bad ones.
4. Real-life examples – code you will write in real apps
Example 1 – User access level / subscription status
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let isLoggedIn = true let hasPremium = false let trialDaysLeft = 0 if !isLoggedIn { print("Please sign in to continue") } else if hasPremium { print("Welcome back, Premium member! Enjoy all features 🎖️") } else if trialDaysLeft > 0 { print("Your trial is active — \(trialDaysLeft) days remaining ✨") } else { print("Welcome! Upgrade to Premium for more features?") } |
This is one of the most common if…else if…else patterns in real apps.
Example 2 – Mini grade calculator (classic teaching + real pattern)
|
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)") |
Example 3 – Weather + rain advice
|
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 29 30 31 32 33 34 |
let temperature = 33.5 let isRaining = false let hasUmbrella = true var advice = "" if temperature > 38 { advice = "Extreme heat warning! Stay indoors 🏠💧" } else if temperature > 32 { advice = "Very hot – drink lots of water 🥵" } else if temperature > 26 { advice = "Warm and sunny – light clothes 😎" } else if temperature > 18 { advice = "Pleasant weather – enjoy the day 🌤️" } else { advice = "It's cold – wear warm layers ❄️" } if isRaining { if hasUmbrella { advice += "\nGood – you have an umbrella ☔" } else { advice += "\nDon't forget to take an umbrella! ☔" } } else { advice += "\nNo rain today – perfect!" } print("Today's advice:\n\(advice)") |
Example 4 – Age-based content restriction
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let age = 15 let hasParentalConsent = true if age >= 18 { print("Full access granted – enjoy all content") } else if age >= 13 && hasParentalConsent { print("Teen mode enabled – some content restricted") } else if age >= 13 { print("Parental consent required for teen mode") } else { print("Sorry – this app is for users 13 years and older") } |
5. Very Important Rules & Best Practices
Rule 1 – Order is critical
Always put the most restrictive / highest value conditions first.
Wrong order example:
|
0 1 2 3 4 5 6 7 |
if age >= 13 { print("Teen mode") } else if age >= 18 { print("Adult mode") } // ← never reached! |
Correct:
|
0 1 2 3 4 5 6 7 |
if age >= 18 { print("Adult mode") } else if age >= 13 { print("Teen mode") } |
Rule 2 – Prefer positive conditions
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Harder to read if !isLoggedIn { showLogin() } // Much easier if isLoggedIn { showDashboard() } else { showLogin() } |
Rule 3 – Use guard instead of deep nesting (very modern & strongly recommended)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
func showContent(user: User?, isPremium: Bool) { guard let user else { print("Please sign in") return } guard user.age >= 13 else { print("Age restriction") return } // happy path – user exists and is old enough if isPremium { print("Premium content unlocked 🎖️") } else { print("Basic content – upgrade for more ✨") } } |
guard makes code much flatter and easier to follow.
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 | higher condition after lower one | 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 |
| Forgetting final else can be missing | assuming something always happens | It’s ok — sometimes you only care about true cases | Intent is clear |
7. Quick Reference – if…else if…else patterns you will use most
| Situation | Typical pattern | Example |
|---|---|---|
| Simple yes/no | if … { … } else { … } | if isRaining { takeUmbrella() } else { walk() } |
| Multiple ranges / levels | if … else if … else if … else { … } | temperature, grade, score, age checks |
| 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 😊
