DEV Community

Gamya
Gamya

Posted on

Swift Switch Statementsโ€”A Cleaner Way to Handle Multiple Conditions ๐Ÿ”€

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

See the problems here?

  • We wrote .ninjutsu twice 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!")
}
Enter fullscreen mode Exit fullscreen mode

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 current once 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
}
Enter fullscreen mode Exit fullscreen mode
  • switch followed by the value you want to check
  • Each case is 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...")
}
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ Always put default last. 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")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Abilities unlocked:
โ€” Chakra Mastery
โ€” Basic Ninjutsu
โ€” Academy Fundamentals
Enter fullscreen mode Exit fullscreen mode

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 โ€” fallthrough is 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.")
}
Enter fullscreen mode Exit fullscreen mode

Output:

๐Ÿ† Mission complete! Experience gained.
Enter fullscreen mode Exit fullscreen mode

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:

  • switch checks 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 fallthrough only when you genuinely need to continue into the next case
  • With enums, switch is 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, switch is cleaner than a chain of else 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)