Exhaustive Switch on Values
Cover all cases or use a default branch.
What switch Does
A switch compares a value against several cases and runs the first matching one. It is a clear alternative to long if/else-if chains.
let day = 3
switch day {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
default:
print("Other")
}No Implicit Fallthrough
Unlike C, Swift cases do not fall through automatically. After a matching case runs, the switch ends. No break needed.
let n = 1
switch n {
case 1:
print("one")
case 2:
print("two")
default:
print("many")
}All lessons in this course
- Exhaustive Switch on Values
- Matching Ranges and Tuples
- Value Binding and where Clauses
- Compound Cases and Fallthrough