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 (0)