Chapter 43: Swift If…Else
1. What is if…else?
if…else is the most fundamental way to make decisions in code.
It answers the question:
“If this condition is true, do this block of code. Otherwise (else), do something different (or do nothing).”
Basic structure:
|
0 1 2 3 4 5 6 7 8 9 10 |
if condition { // code to run if condition is true } else { // code to run if condition is false } |
The else part is optional.
2. Very first examples – try these right now
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let temperature = 32 if temperature > 30 { print("It's really hot 🥵") } else { print("The weather is nice 🌤️") } |
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let age = 17 if age >= 18 { print("You can vote ✓") } // no else → do nothing if false |
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let isRaining = true if isRaining { print("Take umbrella ☔") } else { print("Nice day for a walk 🌞") } |
3. else if — checking multiple conditions
When you have more than two possibilities, use else if.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let temperature = 28 if temperature > 35 { print("Extreme heat warning! 🔥") } else if temperature > 30 { print("Very hot day ☀️") } else if temperature > 25 { print("Warm and pleasant 😊") } else if temperature > 15 { print("Cool weather 🧥") } else { print("It's cold! ❄️") } |
Important rules about else if:
- Swift checks conditions from top to bottom
- As soon as one condition is true, it runs that block and skips all the rest
- You can have as many else if as you want
- The final else (optional) catches everything else
4. Real-life examples – the kind of code you will actually write
Example 1 – Simple 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! 🎖️") } else { print("Welcome back! Consider Premium for more features ✨") } } else { print("Please sign in to continue") } |
Example 2 – Form validation (very common in apps)
|
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 35 |
let email = "aarav@example.com" let password = "Secure123!" let termsAccepted = true var errors: [String] = [] if email.isEmpty { errors.append("Email is required") } else if !email.contains("@") || !email.contains(".") { errors.append("Please enter a valid email") } if password.isEmpty { errors.append("Password is required") } else if password.count < 8 { errors.append("Password must be at least 8 characters") } if !termsAccepted { errors.append("You must accept the terms") } if errors.isEmpty { print("Form is valid – creating account…") } else { print("Please fix the following errors:") for error in errors { print("• \(error)") } } |
Example 3 – Temperature / weather 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 |
let temperatureCelsius = 33.2 let isRaining = false if temperatureCelsius >= 38 { print("Dangerous heat! Stay indoors 🏠💧") } else if temperatureCelsius >= 32 { print("Very hot — drink lots of water 🥤") } else if temperatureCelsius >= 25 { print("Warm day — light clothes 😎") } else if temperatureCelsius >= 15 { print("Pleasant weather — perfect for a walk 🌳") } else { print("It's cold — wear a jacket 🧥") } if isRaining { print("Don't forget umbrella ☔") } |
Example 4 – Score / grade system (very typical)
|
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 – Conditions 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 – Avoid very deep nesting
Bad (hard to read):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
if user != nil { if user!.isPremium { if user!.hasSubscription { // … } } } |
Better:
|
0 1 2 3 4 5 6 7 8 9 |
guard let user else { return } guard user.isPremium else { return } guard user.hasSubscription else { return } // happy path |
6. Very Common Beginner Mistakes & Fixes
| Mistake | Wrong code | Correct / Better way | Why? |
|---|---|---|---|
| Using = instead of == | if age = 18 { … } | if age == 18 { … } | = is assignment — compile error here |
| Writing == true everywhere | if isAdult == true { … } | if isAdult { … } | Cleaner & idiomatic |
| Forgetting else if chain order | if score >= 80 { “A” } else if score >= 90 { “A+” } | Put higher conditions first | First true condition wins |
| Deep nesting instead of guard/early return | many nested ifs | Use guard or early return | Flatter, easier to read code |
| Comparing optionals incorrectly | if optional == 10 { … } | if let value = optional, value == 10 { … } | Direct comparison with nil is usually wrong |
7. Quick Reference – if patterns you will use most
| Situation | Recommended pattern | Example |
|---|---|---|
| Simple yes/no | if condition { … } else { … } | if isRaining { … } else { … } |
| Multiple ranges | if … else if … else if … else { … } | grade / temperature checks |
| Early exit / validation | guard condition else { return } | guard let user else { return } |
| Optional unwrapping + check | if let value = optional, value > 10 { … } | Safe optional handling |
| Short one-liner | if condition { doSomething() } | if isLoading { showSpinner() } |
8. Small Practice – Try these
- Write code that prints different messages based on temperature:
-
35 → “Extreme heat”
- 30…35 → “Very hot”
- 25…30 → “Warm”
- else → “Cool”
-
- Create a simple login check:
- if not logged in → “Please sign in”
- if logged in but not premium → “Welcome! Get Premium?”
- if premium → “Welcome Premium member!”
- Write a mini grade calculator: marks ≥ 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 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)
- Combining if with optionals (if let, if case let, etc.)
- if in SwiftUI (conditional views)
- Or move to another topic (loops, functions, arrays, optionals…)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
