In our last article we learned how if lets Swift make a single decision. But real apps rarely deal with just one condition โ you need to handle multiple outcomes, combine checks, and deal with complex logic.
That's what this article is all about. ๐ง
๐ The Problem with Multiple if Statements
Let's say you're checking a shinobi's rank based on their power level:
let powerLevel = 9001
if powerLevel > 9000 {
print("It's over 9000! ๐ฅ")
}
if powerLevel <= 9000 {
print("Not quite there yet...")
}
This works โ but it's wasteful. Swift has to check powerLevel twice, even though the two conditions can never both be true at the same time. For a simple integer that's fine, but imagine if the check involved something complex like fetching data or running a calculation โ you'd be doing that work twice for no reason.
There's a better way. โ
๐ Using else
else means "if the condition above was false, run this instead":
let powerLevel = 9001
if powerLevel > 9000 {
print("It's over 9000! ๐ฅ")
} else {
print("Not quite there yet...")
}
Now Swift checks powerLevel once. If it's over 9000, the first block runs. Otherwise, the else block runs. Cleaner, faster, easier to read. ๐ธ
๐ช Using else if โ Handling More Outcomes
What if you need more than two outcomes? That's where else if comes in โ it lets you chain additional checks:
let powerLevel = 9000
if powerLevel > 9000 {
print("It's over 9000! ๐ฅ")
} else if powerLevel == 9000 {
print("It's exactly 9000!")
} else {
print("Still training...")
}
Output:
It's exactly 9000!
Swift works through the conditions top to bottom and stops as soon as one is true. The rules are:
- You must have exactly one
ifto start - You can have as many
else ifblocks as you need - You can have zero or one
elseat the end โ it catches everything that didn't match above
โ ๏ธ Without
else if, you'd end up with nestedifstatements insideelseblocks โ which works but gets messy fast.else ifkeeps everything flat and readable.
๐ Combining Conditions with && (AND)
Sometimes one condition isn't enough โ you want both things to be true at the same time.
Use && (read as "and") to combine two conditions. The whole check only passes if both sides are true:
let temperature = 25
if temperature > 20 && temperature < 30 {
print("Perfect weather for training outside! โ๏ธ")
}
Output:
Perfect weather for training outside! โ๏ธ
If either side is false, the whole condition is false. Both must be true for the block to run.
๐ Combining Conditions with || (OR)
Use || (read as "or") when you want the condition to pass if at least one side is true:
let userAge = 14
let hasParentalConsent = true
if userAge >= 18 || hasParentalConsent {
print("You can access this content.")
}
Output:
You can access this content.
The user is only 14 โ so the first part fails. But they have parental consent โ so the second part passes. With ||, one passing side is enough. โ
โ ๏ธ Mixing && and || โ Be Careful!
Here's where things can get tricky. Look at this condition:
if isOwner && isEditingEnabled || isAdmin {
print("You can delete this post.")
}
Does that mean:
- (isOwner AND editingEnabled) OR isAdmin โ admins can always delete
- isOwner AND (editingEnabled OR isAdmin) โ only owners can delete
These are two completely different things! Swift will always pick the first interpretation (it reads && before ||), but relying on that is a bad habit.
Always use parentheses to make your intent clear:
// Clear version โ admins can always delete, owners can delete if editing is on
if (isOwner && isEditingEnabled) || isAdmin {
print("You can delete this post.")
}
Any time you mix && and || in the same condition, add parentheses. Your future self will thank you. ๐
๐ฎ Enums + Conditions โ A Perfect Combo
Enums and conditions work beautifully together. Here's a battle system that shows off if, else if, else, and || all at once:
enum BattleStyle {
case ninjutsu, taijutsu, genjutsu, swordplay, summon
}
let sasukesStyle = BattleStyle.ninjutsu
if sasukesStyle == .ninjutsu || sasukesStyle == .genjutsu {
print("Sasuke is using chakra-based techniques! โก")
} else if sasukesStyle == .taijutsu {
print("Sasuke is fighting hand to hand! ๐")
} else if sasukesStyle == .swordplay {
print("Sasuke drew the Kusanagi blade! โ๏ธ")
} else {
print("Sasuke called upon a summoning! ๐")
}
Output:
Sasuke is using chakra-based techniques! โก
A few things worth noticing:
- We need to write
BattleStyle.ninjutsuthe first time to tell Swift which enum we mean - After that, Swift knows
sasukesStyleis aBattleStyle, so we can just write.genjutsu,.taijutsu, etc. -
||lets us check for two enum cases in a single condition โ if either matches, the block runs - Swift checks top to bottom and stops at the first match โ only one block ever runs
๐งฉ Putting It All Together
Here's a more complete example โ a shinobi ranking system:
let chakra = 85
let missionsCompleted = 47
let isAnbu = false
if chakra >= 90 && missionsCompleted >= 50 {
print("Rank: Jonin ๐")
} else if (chakra >= 70 && missionsCompleted >= 20) || isAnbu {
print("Rank: Chunin โ๏ธ")
} else if chakra >= 50 {
print("Rank: Genin ๐")
} else {
print("Rank: Academy Student ๐")
}
Output:
Rank: Chunin โ๏ธ
The first condition fails โ chakra is 85 but missions is only 47. The second condition passes โ chakra is over 70 and missions is over 20. Swift stops there and runs that block.
๐ Wrap Up
Here's everything we covered:
| Tool | What it does |
|---|---|
else |
Runs if the if condition was false |
else if |
Checks a new condition if the previous one was false |
&& |
Both conditions must be true |
OR operator (two pipe symbols) |
At least one condition must be true |
() parentheses |
Makes the order of checks explicit and clear |
A few golden rules to remember:
-
elsecatches everything that didn't match โ you can only have one -
else iflets you chain as many checks as you need - Always add parentheses when mixing
&&and||โ don't leave it to Swift to guess - Swift stops at the first true condition โ only one block ever runs
Conditions are the foundation of all app logic โ master these and you'll be able to build almost anything. ๐ช
Next up, we'll look at switch statements โ a cleaner way to handle many conditions at once. See you there! ๐
Top comments (0)