Chapter 46: Swift else
1. What does else actually mean?
else means “otherwise” or “in all other cases”.
It is the fallback branch that runs when the if condition (and all else if conditions) are false.
So the full mental model is:
- if this is true → do this
- else if that is true → do that
- else (none of the above are true) → do this instead
The else block is optional — you can have an if without any else.
2. Very first examples – let’s feel what else does
Example 1 – Very basic
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let temperature = 26 if temperature > 30 { print("It's hot 🥵") } else { print("The weather is comfortable 😊") } |
- temperature = 33 → prints “It’s hot 🥵”
- temperature = 26 → prints “The weather is comfortable 😊”
The else block is the safety net — it catches every case that did not satisfy the if.
Example 2 – No else (nothing happens when false)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let age = 16 if age >= 18 { print("You can vote ✓") } // no else → if age < 18, nothing is printed |
This is very common when you only care about one specific case and want to ignore all others.
3. else with else if — the chain pattern
This is the most classic and most frequently written form in real apps.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let score = 82 if score >= 90 { print("Excellent! A+ 🎉") } else if score >= 80 { print("Very good – A 👍") } else if score >= 70 { print("Good – B 😊") } else if score >= 60 { print("Pass – C 🙂") } else { print("You need to study more… let's work together 📚") } |
How Swift reads this chain:
- Is score ≥ 90? → No
- Is score ≥ 80? → Yes → print “Very good – A 👍” → stops here — never looks at the rest
Important rule #1 about else if chains:
The first true condition wins — everything after it is ignored.
That’s why you must put the highest / most specific conditions first.
Wrong order example (very common mistake):
|
0 1 2 3 4 5 6 7 8 9 10 |
if score >= 60 { print("C") // ← this runs for 82 → wrong! } else if score >= 80 { print("A") // ← never reached! } |
Correct order — always highest first:
|
0 1 2 3 4 5 6 7 8 9 10 |
if score >= 90 { print("A+") } else if score >= 80 { print("A") } else if score >= 70 { print("B") } else if score >= 60 { print("C") } else { print("Fail") } |
4. Real-life examples — code you will actually write
Example 1 – User status / subscription check
|
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 left ✨") } else { print("Welcome! Upgrade to Premium for more features?") } |
Example 2 – Temperature advice (classic teaching + real pattern)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
let temp = 34.8 let feelsLike = 38.2 if temp > 38 || feelsLike > 42 { print("Dangerous heat! Stay indoors and drink water 🏠💧") } else if temp > 32 || feelsLike > 36 { print("Very hot day – avoid direct sun and stay hydrated 🥵") } else if temp > 26 { print("Warm and sunny – light clothes are perfect 😎") } else if temp > 18 { print("Pleasant weather – enjoy the day 🌤️") } else { print("It's cold – wear warm layers ❄️") } |
Example 3 – Simple age-based message
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let age = 15 if age >= 18 { print("You are an adult – you can vote and drive 🚗") } else if age >= 13 { print("You are a teenager – enjoy school and friends 👩🎓") } else { print("You are still a child – lots of fun ahead! 🎈") } |
Example 4 – Mini discount 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 25 |
let totalAmount: Double = 5499.99 var discountPercent = 0.0 if totalAmount >= 10000 { discountPercent = 0.20 } else if totalAmount >= 5000 { discountPercent = 0.15 } else if totalAmount >= 2000 { discountPercent = 0.10 } else { discountPercent = 0.05 } let discountAmount = totalAmount * discountPercent let finalPrice = totalAmount - discountAmount print("Total: ₹\(totalAmount, format: .number.precision(.fractionLength(2)))") print("Discount: \(Int(discountPercent * 100))% → ₹\(discountAmount, format: .number.precision(.fractionLength(2)))") print("You pay: ₹\(finalPrice, format: .number.precision(.fractionLength(2)))") |
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 when you want 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 showProfile(user: User?) { guard let user else { print("No user logged in") return } guard user.age >= 13 else { print("Content not suitable for your age") return } // happy path – user exists and is old enough print("Welcome, \(user.name)! Here's your profile.") } |
guard makes code much flatter and easier to follow.
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 directly | if optional == 10 { … } | if let value = optional, value == 10 { … } | optional == 10 usually means you forgot nil |
7. Quick Reference – if…else 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 😊
