Swift Pattern Matching Example

1. Introduction

Pattern matching in Swift provides a way to access the individual components of data structures, allowing for more expressive and concise code. Swift's switch statement, combined with tuples, enums, and other constructs, offers powerful pattern matching capabilities.

2. Source Code Example

// Define an enum for a simple Traffic Light system
enum TrafficLight {
    case red, yellow, green

// Using switch and pattern matching to handle each case
func trafficLightAction(for light: TrafficLight) {
    switch light {
    case .red:
    case .yellow:
        print("Get Ready!")
    case .green:

// Example using tuples and pattern matching
let point = (x: 1, y: -1)
switch point {
case (0, 0):
    print("Point is at the origin.")
case (_, 0):
    print("Point is on the x-axis.")
case (0, _):
    print("Point is on the y-axis.")
case let (x, y) where x == y:
    print("Point is on the line y=x.")
case let (x, y) where x == -y:
    print("Point is on the line y=-x.")
    print("Point is somewhere else.")

// Calling the function
trafficLightAction(for: .red)


Point is on the line y=-x.

3. Step By Step Explanation

1. We first define an enum named TrafficLight that represents different states of a traffic light.

2. The trafficLightAction(for:) function uses the switch statement to perform pattern matching on the provided TrafficLight value. Depending on the value, a specific instruction is printed.

3. Next, we provide an example of pattern matching with tuples. Here, we define a point tuple representing a point in a 2D plane.

4. Using the switch statement, we then match the tuple against different patterns to determine the point's location. The underscores (_) in the patterns denote a wildcard match, where we don't care about the exact value.

5. The case let syntax allows us to bind matched values to local constants. The where clause further refines the pattern by adding conditions.

6. Finally, we call the trafficLightAction(for:) function and provide .red as the argument.

Through pattern matching in Swift, we can express complex conditional logic in a clear and readable manner. It allows for more precise and descriptive code structures.