← Back to Swift Course | Chapter 3: Control Flow | Lesson 3 of 8

Switch Statement Basics

A switch statement checks a value against a list of possible matches and runs the code for whichever one fits.

Basic Switch Syntax

A switch statement evaluates a value once and matches it against a series of case patterns, running only the matching block.

Example: Basic Switch Syntax

markup
let day = 3
switch day {
case 1:
    print("Monday")
case 2:
    print("Tuesday")
case 3:
    print("Wednesday")
default:
    print("Some other day")
}

Matching Multiple Values in One Case

A single case can match several values at once by separating them with commas.

Example: Matching Multiple Values in One Case

markup
let letter: Character = "a"
switch letter {
case "a", "e", "i", "o", "u":
    print("\(letter) is a vowel")
default:
    print("\(letter) is a consonant")
}

No Implicit Fallthrough

Unlike C or Java, Swift's switch cases do not fall through to the next case by default -- only the matching case's code runs.

Note: If you truly want fallthrough behavior, add the fallthrough keyword explicitly at the end of a case.

Example: No Implicit Fallthrough

markup
let number = 2
switch number {
case 1:
    print("one")
case 2:
    print("two")
case 3:
    print("three")
default:
    print("other")
}
Common Mistakes
  1. Forgetting that Swift's switch must be exhaustive -- every possible value must be handled, often requiring a default case.
  2. Expecting implicit fallthrough between cases like in C; Swift cases do NOT fall through automatically unless you write fallthrough explicitly.
  3. Using a switch for a simple two-way boolean check where an if-else would be simpler and clearer.
Chapter Summary
  • switch compares a value against multiple case patterns and runs the matching one.
  • Swift switches must be exhaustive; a default case covers any remaining values.
  • Unlike C, cases do not fall through to the next case automatically.
  • Multiple values can be matched in one case using a comma-separated list.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.