typestar

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

  1. case ..<5 matches a partial range.
  2. case let g where g > 25 binds and guards at once.
  3. Tuples destructure in the case: ("windward", let rounding).

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Control flow, step 5 of 27 in Language basics.

← Previous Next →