Pattern Matching in Swift: A Concise Guide

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
June 1, 2024

Working with Pattern Matching in Swift

Pattern matching is a powerful feature in Swift that allows you to match and extract values from data structures like arrays, tuples, and enums. It is used in switch statements, if case statements, and for loops to provide concise and expressive code for handling different cases efficiently. Let's explore how to work with pattern matching in Swift.

Switch Statement with Pattern Matching

let name = "Alice"

switch name {
    case "Alice":
        print("Hello, Alice!")
    case "Bob":
        print("Hello, Bob!")
    default:
        print("Hello, stranger!")
}
In this example, we use a switch statement with pattern matching to check the value of the variable `name` and print a corresponding message based on the match.

If Case Statement with Pattern Matching

let point = (x: 3, y: 4)

if case (3, 4) = point {
    print("Point is at (3, 4)")
}
Here, we use an if case statement with pattern matching to check if the variable `point` matches the tuple `(3, 4)`.

For Loop with Pattern Matching

let coordinates = [(1, 2), (3, 4), (5, 6)]

for case let (x, y) in coordinates {
    print("x: \(x), y: \(y)")
}
In this example, we use a for loop with pattern matching to extract and print the `x` and `y` values from each tuple in the `coordinates` array.

Conclusion

Pattern matching in Swift provides a flexible and concise way to handle different cases in your code. Whether you are working with switch statements, if case statements, or for loops, pattern matching allows you to extract values and perform actions based on specific patterns. Experiment with pattern matching in your own Swift projects to see how it can simplify your code and make it more readable.