← Back to Swift Course | Chapter 3: Control Flow | Lesson 8 of 8

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.

Matching Tuples

A switch can match against a tuple's shape, and case let bindings let you extract its individual components.

Example: Matching Tuples

markup
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))")
}

Matching Ranges

A case can match a value against a numeric range, which is useful for grouping values into categories.

Example: Matching Ranges

markup
let score = 85
switch score {
case 90...100:
    print("Grade: A")
case 80..<90:
    print("Grade: B")
default:
    print("Grade: C or below")
}

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

markup
let value: Int? = 7
if case .some(let number) = value {
    print("Got a number: \(number)")
}
Common Mistakes
  1. Thinking pattern matching is only for switch on enums; it also works with tuples, ranges, and optional binding.
  2. Forgetting that a case let pattern binds new local constants that only exist within that case's body.
  3. Overlooking that case order matters -- a broader pattern earlier in a switch will shadow a more specific one written after it.
Chapter Summary
  • Pattern matching in Swift appears in switch, if case, and for case constructs.
  • Tuple patterns can match multiple values and destructure them at once.
  • Range patterns (case 1...5) match a value falling within that range.
  • if case lets 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.