Lesson 5 / 25
Control Flow and Pattern Matching
Use if, switch, loops and ranges, including powerful switch patterns.
Branches, loops and patterns
Swift has if, guard, while, repeat-while and for-in loops over sequences and ranges: 1...5 (closed) and 0..<count (half-open), with stride(from:to:by:) for steps. switch is much more powerful than in C-family languages: it must be exhaustive, cases do not fall through (no break needed), and cases can match ranges (case 90...100), tuples (case (0, _)), enum cases with associated values (case .failed(let reason)), and add conditions with where. Since Swift 5.9, if and switch can be expressions that produce a value (let label = if score >= 40 { "pass" } else { "fail" }). Loops support where clauses and labelled statements for breaking out of nested loops. defer blocks run when the current scope exits, useful for cleanup.
switch with ranges, tuples and where
Exhaustive matching with no fall-through.
func grade(for marks: Int) -> String {
switch marks {
case 85...100: "A"
case 70..<85: "B"
case 40..<70: "C"
case 0..<40: "Fail"
default: "Invalid"
}
}
func quadrant(_ point: (x: Int, y: Int)) -> String {
switch point {
case (0, 0): "origin"
case (_, 0), (0, _): "on an axis"
case let (x, y) where x > 0 && y > 0: "first quadrant"
default: "elsewhere"
}
}
for i in stride(from: 0, to: 10, by: 3) { // 0, 3, 6, 9
print(i)
}
let status = if grade(for: 72) == "Fail" { "retake" } else { "promoted" } // if expressionSorting letters at a post office
A Swift switch is a sorting rack that refuses to accept a letter unless there is a slot for every possible address. You cannot forget a case, and each letter goes into exactly one slot.
Quick check: Which statement about Swift switch is true?
- Cases fall through by default
- switch must be exhaustive and cases do not fall through
- switch only works with integers
- Every case needs break
Answer
switch must be exhaustive and cases do not fall through — Exhaustiveness and no implicit fall-through make switch safer than in C.