Pattern Matching
Pattern matching is a powerful way to check if a value fits a certain shape, and pull out its pieces at the same time.
In this page:
Matching Tuples
A switch can match against a tuple's shape, and case let bindings let you extract its individual components.
Example: Matching Tuples
let coordinate = (0, 5)
switch coordinate {
case (0, 0):
print("Origin")
case (0, let y):
print("On the y-axis at \(y)")
case (let x, 0):
print("On the x-axis at \(x)")
case let (x, y):
print("At (\(x), \(y))")
}
Login to try C/C++/Java/PHP code in the editor
Matching Ranges
A case can match a value against a numeric range, which is useful for grouping values into categories.
Example: Matching Ranges
let score = 85
switch score {
case 90...100:
print("Grade: A")
case 80..<90:
print("Grade: B")
default:
print("Grade: C or below")
}
Login to try C/C++/Java/PHP code in the editor
if case for Single-Value Matching
When you only need to test one pattern without a full switch, if case provides a lightweight alternative.
Example: if case for Single-Value Matching
let value: Int? = 7
if case .some(let number) = value {
print("Got a number: \(number)")
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Thinking pattern matching is only for
switchon enums; it also works with tuples, ranges, and optional binding. - Forgetting that a
case letpattern binds new local constants that only exist within that case's body. - Overlooking that case order matters -- a broader pattern earlier in a
switchwill shadow a more specific one written after it.
Chapter Summary
- Pattern matching in Swift appears in
switch,if case, andfor caseconstructs. - Tuple patterns can match multiple values and destructure them at once.
- Range patterns (
case 1...5) match a value falling within that range. if caselets you pattern-match a single value without a full switch statement.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: