Chapter 52: Swift Switch
1. Why use switch instead of if…else if?
switch is usually cleaner and safer when you have many possible discrete values to check.
Typical situations where switch wins:
- Checking one value against many exact possibilities (enum cases, string options, status codes…)
- You want exhaustive checking (compiler warns if you forget a case)
- You want cleaner vertical flow instead of long else if chains
- You need multiple matching patterns (ranges, tuples, enums with associated values…)
switch is not just a replacement for if — it has different superpowers.
2. Basic switch syntax – the skeleton
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
switch value { case value1: // code for value1 case value2, value3: // multiple matching values // code for value2 or value3 case value4...value10: // range // code for values in range default: // runs if nothing above matched } |
Key rules you must remember:
- Every possible value must be covered (or you need default) → compiler error if missing cases (when switching on enum without default)
- No implicit fallthrough (unlike C/C++) → each case ends automatically
- You can have multiple values in one case (case 1, 3, 5:)
- You can use ranges, tuples, enums with associated values, etc.
3. Very first examples – feel the difference
Example 1 – Basic enum switch
|
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 |
enum Weather { case sunny case cloudy case rainy case snowy } let today = Weather.rainy switch today { case .sunny: print("Wear sunglasses ☀️") case .cloudy: print("Maybe a light jacket 🧥") case .rainy: print("Take umbrella ☔") case .snowy: print("Wear warm coat & boots ❄️") } |
Example 2 – No default needed when enum is exhaustive
If you switch on a non-exhaustive enum or other types, you need default:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let number = 7 switch number { case 1: print("One") case 2, 3, 4: print("Small number") case 5...10: print("Medium number") default: print("Large or negative") } |
4. Real-life examples – the kind of code you will actually write
Example 1 – HTTP status code handling (very common in networking)
|
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 |
func handleResponse(statusCode: Int) { switch statusCode { case 200...299: print("Success! 🎉") case 400...499: switch statusCode { case 400: print("Bad Request – check parameters") case 401: print("Unauthorized – please sign in") case 403: print("Forbidden – you don't have permission") case 404: print("Not Found – resource doesn't exist") default: print("Client error (\(statusCode))") } case 500...599: print("Server error (\(statusCode)) – try again later") default: print("Unknown status code: \(statusCode)") } } |
Example 2 – App state / screen flow (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 25 26 27 28 29 30 31 |
enum AppState { case loading case success(data: String) case error(message: String) case offline } func updateUI(for state: AppState) { switch state { case .loading: showLoadingIndicator() hideContent() case .success(let data): hideLoadingIndicator() showContent(data) case .error(let message): hideLoadingIndicator() showErrorAlert(message: message) case .offline: hideLoadingIndicator() showOfflineMessage() } } |
Example 3 – User role / permission system
|
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 |
enum UserRole: String { case admin case moderator case member case guest } let role = UserRole.moderator switch role { case .admin: showAdminDashboard() allowAllActions() case .moderator: showModeratorTools() allowContentModeration() case .member: showMemberDashboard() allowStandardActions() case .guest: showLimitedView() promptToSignIn() } |
Example 4 – Temperature + clothing advice (realistic nested switch)
|
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 |
let tempC = 8.0 let isRaining = true switch tempC { case ..<0: print("Freezing! ❄️") print("Wear heavy coat, gloves, scarf") case 0..<10: print("Cold 🥶") if isRaining { print("Rain + cold = take waterproof jacket + umbrella") } else { print("Just a warm jacket") } case 10..<20: print("Cool 😌") print("Light jacket or sweater") case 20...: print("Warm or hot 🌡️") print("T-shirt is enough") default: print("Invalid temperature") } |
5. Very Important Modern Features (2024–2026 style)
Feature 1 – No need for break (automatic break)
Unlike C/C++/Java, Swift does NOT fall through — each case ends automatically.
Feature 2 – Multiple matching values in one case
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
switch statusCode { case 200, 201, 204: print("Success family") case 400, 401, 403, 404: print("Client error") default: print("Other") } |
Feature 3 – Range matching
|
0 1 2 3 4 5 6 7 8 9 10 11 |
switch percentage { case 90...100: print("A+") case 80..<90: print("A") case 70..<80: print("B") default: print("Other") } |
Feature 4 – switch on optionals (very clean)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
switch optionalUser { case .none: showSignIn() case .some(let user): if user.isPremium { showPremiumContent() } else { showBasicContent() } } |
Or even shorter (pattern matching):
|
0 1 2 3 4 5 6 7 8 |
if case .some(let user) = optionalUser, user.isPremium { // … } |
6. Very Common Beginner Mistakes & Fixes
| Mistake | Wrong code | Correct / Better way | Why? |
|---|---|---|---|
| Forgetting default when needed | switch statusCode { case 200: … } | Add default: | Compile error if not exhaustive (for some types) |
| Expecting fallthrough | case 1: print(“One”) case 2: print(“Two”) | Each case needs its own block | No implicit fallthrough |
| Using if for many exact matches | long else if chain | Use switch | Cleaner, safer (exhaustiveness) |
| Forgetting to handle all enum cases | switch role { case .admin: … } | Add all cases or default | Compiler warns / errors |
| Nested switch hell | switch inside switch inside switch | Flatten with guard or combine conditions | Hard to read & maintain |
7. Quick Summary – When to prefer switch over if…else if
| Situation | Prefer switch? | Prefer if…else? | Reason / guideline |
|---|---|---|---|
| Checking many exact values (enum, status codes) | Yes | — | Exhaustive checking, cleaner |
| Matching ranges | Yes | Sometimes | switch handles ranges very nicely |
| More than 4–5 conditions | Yes | — | Easier to read & maintain |
| Optional unwrapping + matching | Yes | — | case .some(let x): is very clean |
| Complex boolean combinations | — | Yes | `if a && (b |
| Early exit / validation | — | Yes (guard) | guard is designed for this |
8. Small Practice – Try these
- Write a switch that gives grade based on percentage:
- 90…100 → “A+”
- 80..<90 → “A”
- 70..<80 → “B”
- 60..<70 → “C”
- else → “Fail”
- Write a switch on enum UserRole (admin, moderator, member, guest)
- admin → full access
- moderator → content tools
- member → normal view
- guest → limited view + sign-in prompt
- Write a function that returns weather advice using switch on temperature ranges
Paste your code here if you want feedback or want to see even cleaner versions!
What would you like to explore next?
- switch with associated values (very powerful with enums)
- guard statement (the modern companion to if)
- if let / optional binding in depth
- 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 😊
