Switch Statement Basics
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
let day = 3
switch day {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
default:
print("Some other day")
}
Login to try C/C++/Java/PHP code in the editor
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
let letter: Character = "a"
switch letter {
case "a", "e", "i", "o", "u":
print("\(letter) is a vowel")
default:
print("\(letter) is a consonant")
}
Login to try C/C++/Java/PHP code in the editor
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
let number = 2
switch number {
case 1:
print("one")
case 2:
print("two")
case 3:
print("three")
default:
print("other")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting that Swift's
switchmust be exhaustive -- every possible value must be handled, often requiring adefaultcase. - Expecting implicit fallthrough between cases like in C; Swift cases do NOT fall through automatically unless you write
fallthroughexplicitly. - Using a
switchfor a simple two-way boolean check where anif-elsewould be simpler and clearer.
switchcompares a value against multiplecasepatterns and runs the matching one.- Swift switches must be exhaustive; a
defaultcase 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: