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

Collapse
 
junhao profile image
Jun Hao

🌸🌸🌸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. πŸ’«πŸŒΉ

Collapse
 
gamya_m profile image
Gamya

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! 🌹✨

Collapse
 
junhao profile image
Jun Hao

🌸🌸🌸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! πŸš€βœ¨

Thread Thread
 
gamya_m profile image
Gamya

Aww thank you so much!! 🌸 Your comments always brighten my day β€” the next one is on its way, stay tuned! πŸš€βœ¨

Thread Thread
 
junhao profile image
Jun Hao

Best Regard

Some comments may only be visible to logged-in visitors. Sign in to view all comments.