Switch Statement Basics
switch value {
case pattern1:
// code
case pattern2, pattern3:
// code
default:
// code
}
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
// Declare a constant `day`, set to `3`
let day = 3
// Switch on `day` and branch by case
switch day {
// Case: `1`
case 1:
// Print "Monday" to the console
print("Monday")
// Case: `2`
case 2:
// Print "Tuesday" to the console
print("Tuesday")
// Case: `3`
case 3:
// Print "Wednesday" to the console
print("Wednesday")
default:
// Print "Some other day" to the console
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
// Declare a constant `letter` (a Character), set to `"a"`
let letter: Character = "a"
// Switch on `letter` and branch by case
switch letter {
// Case: `"a", "e", "i", "o", "u"`
case "a", "e", "i", "o", "u":
// Print "\(letter) is a vowel" to the console
print("\(letter) is a vowel")
default:
// Print "\(letter) is a consonant" to the console
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.
fallthrough keyword explicitly at the end of a case.Example: No Implicit Fallthrough
// Declare a constant `number`, set to `2`
let number = 2
// Switch on `number` and branch by case
switch number {
// Case: `1`
case 1:
// Print "one" to the console
print("one")
// Case: `2`
case 2:
// Print "two" to the console
print("two")
// Case: `3`
case 3:
// Print "three" to the console
print("three")
default:
// Print "other" to the console
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: