DEV Community

Gamya
Gamya

Posted on

Swiftโ€”Checking Multiple Conditions with else, else if, && and || ๐Ÿ”€

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...")
}
Enter fullscreen mode Exit fullscreen mode

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...")
}
Enter fullscreen mode Exit fullscreen mode

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...")
}
Enter fullscreen mode Exit fullscreen mode

Output:

It's exactly 9000!
Enter fullscreen mode Exit fullscreen mode

Swift works through the conditions top to bottom and stops as soon as one is true. The rules are:

  • You must have exactly one if to start
  • You can have as many else if blocks as you need
  • You can have zero or one else at the end โ€” it catches everything that didn't match above

โš ๏ธ Without else if, you'd end up with nested if statements inside else blocks โ€” which works but gets messy fast. else if keeps 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! โ˜€๏ธ")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Perfect weather for training outside! โ˜€๏ธ
Enter fullscreen mode Exit fullscreen mode

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.")
}
Enter fullscreen mode Exit fullscreen mode

Output:

You can access this content.
Enter fullscreen mode Exit fullscreen mode

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.")
}
Enter fullscreen mode Exit fullscreen mode

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.")
}
Enter fullscreen mode Exit fullscreen mode

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! ๐Ÿ")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Sasuke is using chakra-based techniques! โšก
Enter fullscreen mode Exit fullscreen mode

A few things worth noticing:

  • We need to write BattleStyle.ninjutsu the first time to tell Swift which enum we mean
  • After that, Swift knows sasukesStyle is a BattleStyle, 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 ๐Ÿ“š")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Rank: Chunin โš”๏ธ
Enter fullscreen mode Exit fullscreen mode

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:

  • else catches everything that didn't match โ€” you can only have one
  • else if lets 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)