Swift Pattern Matching Basics

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

by The Captain

on
April 13, 2024
Tutorial: Swift Pattern Matching

Swift Pattern Matching

In Swift, pattern matching is a powerful feature that allows you to check whether a value conforms to a specific pattern. It enables you to match values against a set of predefined patterns or conditions. Pattern matching is commonly used in switch statements, where you can use patterns to match values and execute corresponding code blocks.

One of the most common ways to use pattern matching in Swift is with the switch statement. Here's an example that demonstrates pattern matching with different cases:


        let someValue = 5

        switch someValue {
        case 0:
            print("Value is zero")
        case 1..<5:
            print("Value is between 1 and 4")
        case 5...10:
            print("Value is between 5 and 10")
        default:
            print("Value is something else")
        }
    

In this example, the switch statement checks the value of someValue against different patterns using range operators. If the value matches a specific pattern, the corresponding print statement is executed.

You can also use pattern matching with tuples to match multiple values at once. Here's an example:


        let point = (2, 2)

        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 (1...5, 1...5):
            print("Point is in the first quadrant")
        default:
            print("Point is in another quadrant")
        }
    

This switch statement matches the tuple point against different patterns, such as points on the x-axis, y-axis, and different quadrants in a Cartesian coordinate system.