switch patterns in Swift
Exhaustive matching over ranges, wheres, and tuples.
let windKts = 18
// switch must be exhaustive; ranges and wheres are patterns.
switch windKts {
case ..<5:
print("Drifter conditions")
case 5..<15:
print("Champagne sailing")
case let g where g > 25:
print("Gale watch: \(g) kts")
default:
print("Fresh breeze, hike hard")
}
// Tuples destructure right in the cases.
let mark = ("windward", 1)
switch mark {
case ("windward", let rounding):
print("Rounding \(rounding) at the top mark")
case (let name, _):
print("Passing \(name)")
}
How it works
case ..<5matches a partial range.case let g where g > 25binds and guards at once.- Tuples destructure in the case:
("windward", let rounding).
Keywords and builtins used here
casedefaultletprintswitchwhere
The run, in numbers
- Lines
- 20
- Characters to type
- 482
- Tokens
- 113
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 104 seconds.
Step 2 of 3 in Control flow, step 5 of 27 in Language basics.