Skip to content
AgileLogics
6 min read

The switch Statement

Prerequisites: Conditionals

switch compares one value against several patterns and runs the first one that matches. Swift's switch is far more powerful than in C or Java.

Syntax

switch value {
case pattern1:
    // ...
case pattern2, pattern3:
    // ...
default:
    // anything else
}

Example

let day = "Saturday"

switch day {
case "Saturday", "Sunday":
    print("Weekend!")
case "Friday":
    print("Almost weekend")
default:
    print("Weekday")
}

Expected output

Weekend!

Two rules make Swift's switch safe:

  • No fall-through. Only the matching case runs — there's no break needed, and no accidental running into the next case.
  • It must be exhaustive. Every possible value must be handled. For strings and numbers, that usually means a default case. Leaving it out gives error: switch must be exhaustive.

Ranges and conditions

let score = 84

let grade = switch score {
case 90...100: "A"
case 80..<90: "B"
case 70..<80: "C"
default: "F"
}
print(grade)

let temperature = -3
switch temperature {
case ..<0:
    print("Freezing")
case let t where t > 30:
    print("Hot: \(t)")
default:
    print("Mild")
}
B
Freezing
  • switch can produce a value directly (Swift 5.9+), as with grade.
  • ..<0 is a one-sided range: anything below 0.
  • case let t where ... binds the value to t and adds an extra condition.

switch becomes even more useful with enums, which don't need a default when every case is listed — covered in Level 2.

Practice

Given a month from 1 to 12, print the season (Northern Hemisphere): 12, 1, 2 → winter; 3–5 → spring; 6–8 → summer; 9–11 → autumn.

Show solution
let month = 7

let season = switch month {
case 12, 1, 2: "winter"
case 3...5: "spring"
case 6...8: "summer"
case 9...11: "autumn"
default: "invalid month"
}
print(season)
summer