switch / case / where / fallthrough
Swift's switch statement is a powerful control flow construct that performs pattern matching against a value. Unlike C, it has no implicit fallthrough and must be exhaustive.
Syntax
switch value {
case pattern1:
// process
case pattern2, pattern3:
// multiple patterns
case pattern4 where condition:
// narrowed by where clause
default:
// none of the above matched
}
Syntax Reference
| Syntax | Description |
|---|---|
| case value: | Handles the case when the value matches the specified value. |
| case value1, value2: | Handles multiple values in a single case. |
| case range: | Matches a numeric range (e.g., 1...5). |
| case let x where condition: | Binds the value and adds a condition with a where clause. |
| case (x, y): | Performs pattern matching on a tuple. |
| default: | Handles the case when none of the other cases match. |
| fallthrough | Transfers control to the next case (must be specified explicitly). |
Sample Code
// Basic switch
let day = 3
switch day {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4, 5:
print("Thursday or Friday")
case 6, 7:
print("Weekend")
default:
print("Invalid value")
}
// Range matching
let score = 85
switch score {
case 90...100:
print("Excellent")
case 70..<90:
print("Good")
case 60..<70:
print("Pass")
default:
print("Fail")
}
// Adding conditions with where clause
let number = 42
switch number {
case let n where n % 2 == 0:
print("\(n) is even")
case let n where n % 2 != 0:
print("\(n) is odd")
default:
break
}
// Tuple pattern matching
let point = (1, 0)
switch point {
case (0, 0):
print("Origin")
case (let x, 0):
print("On the x-axis: x = \(x)")
case (0, let y):
print("On the y-axis: y = \(y)")
case (let x, let y):
print("Coordinate: (\(x), \(y))")
}
Notes
Unlike C, Swift's switch statement automatically stops execution at the end of each matched case — there is no implicit fallthrough. Use the fallthrough keyword explicitly if you want execution to continue into the next case.
A Swift switch must be exhaustive, covering all possible values. When switching on an enum, either list every case or add a default clause. Insufficient exhaustiveness results in a compile error.
For combining with the break statement, see break / continue / return / labeled statement.
If you find any errors or copyright issues, please contact us.