Matching Ranges and Tuples
Switch on numeric ranges and tuple shapes.
Matching a Range
A case can match a whole range of values using range operators like 1...5. If the value falls in the range, the case runs.
let score = 85
switch score {
case 0..<50:
print("Fail")
case 50...100:
print("Pass")
default:
print("Invalid")
}Closed vs Half-Open
Use closed ranges (...) to include the upper bound and half-open ranges (..<) to exclude it. Pick boundaries that do not overlap.
let age = 18
switch age {
case 0..<13:
print("Child")
case 13..<20:
print("Teen")
default:
print("Adult")
}All lessons in this course
- Exhaustive Switch on Values
- Matching Ranges and Tuples
- Value Binding and where Clauses
- Compound Cases and Fallthrough