0Pricing
Swift Academy · Lesson

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

  1. Exhaustive Switch on Values
  2. Matching Ranges and Tuples
  3. Value Binding and where Clauses
  4. Compound Cases and Fallthrough
← Back to Swift Academy