In our last article we learned how to chain if, else if, and else together to handle multiple conditions. But the more conditions you add, the messier it gets. Swift gives us a much cleaner tool for exactly this situation β the switch statement. π§
π¬ The Problem with Long if-else Chains
Let's say you're building a ninja battle system and need to react to different jutsu types:
enum JutsuType {
case ninjutsu, taijutsu, genjutsu, senjutsu, unknown
}
let current = JutsuType.ninjutsu
if current == .ninjutsu {
print("Chakra-based technique!")
} else if current == .taijutsu {
print("Physical combat!")
} else if current == .ninjutsu { // π¬ checked twice by accident!
print("Illusion technique!")
} else {
print("Unknown technique!")
}
See the problems here?
- We wrote
.ninjutsutwice by accident β Swift won't warn us - We never checked
.senjutsuβ that's a missing case Swift won't catch - We keep repeating
current ==over and over β noisy and repetitive
This is exactly the kind of code that causes subtle bugs in real apps. β οΈ
β Enter the Switch Statement
switch solves all three problems at once:
switch current {
case .ninjutsu:
print("Chakra-based technique! β‘")
case .taijutsu:
print("Physical combat! π")
case .genjutsu:
print("Illusion technique! π")
case .senjutsu:
print("Sage Mode activated! πΈ")
case .unknown:
print("Unrecognised technique!")
}
Much cleaner. And Swift is now actively helping you:
- β If you check the same case twice, Swift complains
- β If you miss a case, Swift refuses to build your code
- β
You only write
currentonce at the top β no repetition
π Breaking Down the Syntax
switch valueToCheck {
case possibleValue1:
// code to run
case possibleValue2:
// code to run
default:
// code to run if nothing matched
}
-
switchfollowed by the value you want to check - Each
caseis a value to compare against - A colon after each case marks the start of the code to run
- Swift automatically stops after the first matching case β no accidental fall-through
- A closing
}ends the whole statement
π Switch Must Be Exhaustive
This is the big rule β every possible value must be handled. With enums, Swift knows exactly what cases exist, so it checks for you. With strings or integers (where there are infinite possibilities), you need a default case to catch everything else:
let village = "Hidden Leaf"
switch village {
case "Hidden Leaf":
print("Home of the Hokage! π")
case "Hidden Sand":
print("Home of the Kazekage! ποΈ")
case "Hidden Mist":
print("Home of the Mizukage! π")
default:
print("Unknown village...")
}
β οΈ Always put
defaultlast. If you put it first, Swift will refuse to build β it knows the default would always match and the other cases would never run.
π Switch vs if-else β Which Should You Use?
| Situation | Better choice |
|---|---|
| Checking one or two conditions |
if / else
|
| Checking the same value against 3+ possibilities | switch |
| Working with enums |
switch β exhaustive checking is a lifesaver |
| Need advanced pattern matching | switch |
| Conditions involve different variables |
if / else if
|
A good rule of thumb β if you find yourself writing else if more than twice for the same variable, reach for switch instead. Your code will be cleaner and safer. πΈ
β‘ Switch Only Reads the Value Once
Here's a performance benefit that's easy to overlook. With if-else if, Swift reads your value every time it checks a condition. With switch, it reads the value once at the top and works from there.
For simple variables this doesn't matter much β but when you start using function calls in conditions, those functions run every time with if, which can slow things down. switch avoids that completely.
π The fallthrough Keyword
By default, Swift stops at the first matching case and doesn't run any others. This is different from some other languages that automatically "fall through" to the next case.
But sometimes you actually want that behaviour β and that's what fallthrough is for.
Here's a fun example using an anime power ranking. If a character reaches level 5, they've also achieved everything below it:
let powerRank = 3
print("Abilities unlocked:")
switch powerRank {
case 5:
print("β Legendary Mode")
fallthrough
case 4:
print("β Sage Mode")
fallthrough
case 3:
print("β Chakra Mastery")
fallthrough
case 2:
print("β Basic Ninjutsu")
fallthrough
default:
print("β Academy Fundamentals")
}
Output:
Abilities unlocked:
β Chakra Mastery
β Basic Ninjutsu
β Academy Fundamentals
Swift matches case 3, prints that line, then fallthrough forces it to keep going through each case below. Without fallthrough, only "β Chakra Mastery" would print.
π‘ Be honest though β
fallthroughis pretty rare in real Swift code. Most of the time you won't need it. It's good to know it exists, but don't worry if you can't think of many situations to use it.
π§© Putting It All Together
Here's a complete battle system using switch with an enum:
enum BattleOutcome {
case victory, defeat, draw, retreat, unknown
}
let result = BattleOutcome.victory
switch result {
case .victory:
print("π Mission complete! Experience gained.")
case .defeat:
print("π You've been defeated. Try again.")
case .draw:
print("π€ Neither side won. Regroup.")
case .retreat:
print("π Strategic withdrawal successful.")
case .unknown:
print("β Battle result unclear.")
}
Output:
π Mission complete! Experience gained.
Swift checks each case in order, finds .victory, runs that block, and stops. Clean, safe, and impossible to accidentally miss a case. β
π Wrap Up
Switch statements are one of those things that once you start using them, you'll wonder how you managed without them.
Here's what to remember:
-
switchchecks a value once and matches it against multiple cases - Every switch must be exhaustive β cover all cases or add
default - Swift stops at the first matching case automatically β no accidental fall-through
- Use
fallthroughonly when you genuinely need to continue into the next case - With enums,
switchis almost always the right choice β Swift will catch missed or duplicate cases at compile time - When checking the same value against 3 or more possibilities,
switchis cleaner than a chain ofelse if
Next up, we'll look at the ternary conditional operator β a compact way to make quick decisions in a single line. See you there! π
Top comments (5)
πΈπΈπΈMy Dear Girlπππ
πΈ This is such a wonderful and beautifully written explanation of switch statements. I genuinely enjoyed reading every part of it from start to finish. The examples are creative, engaging, and make learning Swift feel fun and approachable. β¨ I especially loved the comparison between switch and if-else chains because it clearly showed the advantages in a practical way. Your use of ninja and anime-themed examples made the concepts memorable and enjoyable. π The flow of the article is smooth, and each section builds naturally on the previous one. Complex ideas are explained with clarity and simplicity, which is a rare and valuable skill. π· The section on exhaustive checking and fallthrough was particularly helpful and easy to understand. It's clear that a lot of care, knowledge, and effort went into creating this guide. Thank you for sharing such thoughtful and inspiring contentβIβm looking forward to reading more of your wonderful work in the future. π«πΉ
Aww this is the sweetest comment, thank you so much!! πΈπ It genuinely makes me so happy knowing you're enjoying the series and following along β that means everything! The ninja examples are my favourite part to write so I'm glad they're making the concepts stick π More fun articles are on the way, so stay tuned β your support keeps me going! πΉβ¨
πΈπΈπΈMY DEAR GIRLπΈπΈπΈ
πΈYour articles are always enjoyable to read! πΈ The way you explain concepts with fun examples makes learning much easier and more memorable. Looking forward to the next one! πβ¨
Aww thank you so much!! πΈ Your comments always brighten my day β the next one is on its way, stay tuned! πβ¨
Best Regard
Some comments may only be visible to logged-in visitors. Sign in to view all comments.