Chapter 44: If…Else
1. What does if…else actually do?
if…else lets your program make decisions.
It answers questions of the form:
“If this is true, do this. Otherwise (else), do that (or do nothing).”
The condition inside if must be a Bool (true or false).
Basic structure:
|
0 1 2 3 4 5 6 7 8 9 10 |
if condition { // code that runs only when condition is true } else { // code that runs when condition is false } |
The else part is optional — you can have if without else.
2. Very first examples – try these right now
Example A – Simple yes/no
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let temperature = 33 if temperature > 30 { print("It's hot outside 🥵 – stay hydrated!") } else { print("Nice weather 😊 – good time for a walk.") } |
Example B – No else (do nothing if false)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let age = 19 if age >= 18 { print("You can vote ✓") } // nothing happens if age < 18 |
Example C – Boolean directly
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let isRaining = true if isRaining { print("Take umbrella ☔") } else { print("Sunny day 🌞") } |
3. else if — checking several possibilities
When you have more than two cases, 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 > 38 { print("Dangerous heat! Stay indoors 🏠💧") } else if temperature > 32 { print("Very hot day – drink lots of water 🥤") } else if temperature > 26 { print("Warm and pleasant 😎") } else if temperature > 18 { print("Cool weather – light jacket 🧥") } else { print("It's cold! 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 everything below
- Order matters — put the most specific / highest priority conditions first
- The final else (optional) catches all cases that didn’t match above
Wrong order example (common beginner mistake):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let score = 92 if score >= 80 { print("A") // ← this runs → "A" } else if score >= 90 { print("A+") // ← never reached! } |
Correct order:
|
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 – code you will actually write
Example 1 – Login / user status (very typical)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let isLoggedIn = true let hasPremium = false let hasTrial = true if isLoggedIn { if hasPremium { print("Welcome back, Premium member! 🎖️ Enjoy all features.") } else if hasTrial { print("Welcome! Your trial is active – 3 days left.") } else { print("Welcome! Get Premium for more features ✨") } } else { print("Please sign in to continue") } |
Example 2 – Form validation (extremely common)
|
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 36 37 38 39 40 |
let email = "test@example.com" let password = "Pass123!" let age = 17 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 address") } if password.isEmpty { errors.append("Password is required") } else if password.count < 8 { errors.append("Password must be at least 8 characters") } if age < 13 { errors.append("You must be at least 13 years old") } if !termsAccepted { errors.append("You must accept the terms and conditions") } 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 24 25 26 27 28 29 30 31 32 33 |
let temperature = 34.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 and 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 – wear warm layers ❄️" } if isRaining { if hasUmbrella { advice += "\nBut you have an umbrella – good job! ☔" } else { advice += "\nDon't forget to take an umbrella! ☔" } } print("Weather advice:") 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 – 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 – Use guard for early exit (very modern & clean)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
func processUser(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 easier to read — highly recommended.
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 / == 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 incorrectly | if optional == 10 { … } | if let value = optional, value == 10 { … } | optional == 10 is usually not what you want |
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 & concise optional handling |
| Short one-liner | if condition { doSomething() } | if isLoading { showSpinner() } |
8. Small Practice – Try these
- Write code that gives weather advice based on temperature:
-
38 → “Extreme heat! Stay inside”
- 32–38 → “Very hot – drink water”
- 25–32 → “Warm day”
- 15–25 → “Pleasant”
- else → “Cold”
-
- Create a simple login check:
- not logged in → “Please sign in”
- logged in, not premium → “Welcome! Get Premium?”
- logged in + premium → “Welcome Premium member!”
- Write a 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 😊
