Exploring Swift Pattern Matching: Switch, Guard, and Tuples

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

by The Captain

May 26, 2024
Swift Pattern Matching

Swift Pattern Matching

Pattern matching is a powerful feature in Swift that allows you to check if a value has a certain shape and extract values associated with that shape. It provides a way to conditionally execute code based on the structure of a value.

Switch Statement with Pattern Matching

One common use case of pattern matching in Swift is with the switch statement. You can use pattern matching to specify different cases and execute code based on the matched pattern. Here's an example of using pattern matching with a switch statement:

let value: Any = 42

switch value {
case let intValue as Int:
    print("Integer value: \(intValue)")
case let doubleValue as Double:
    print("Double value: \(doubleValue)")
    print("Unknown type")

In this example, we use the `as` keyword to match and bind the value to a specific type within each case of the switch statement.

Guard Statement with Pattern Matching

You can also use pattern matching with the guard statement to safely unwrap optional values and execute code based on certain conditions. Here's an example:

func processValue(value: Any?) {
    guard let intValue as Int = value else {
        print("Value is not an integer")
    print("Integer value: \(intValue)")

In this example, we use pattern matching in the guard statement to safely unwrap an optional value as an integer type.

Matching Tuples

Pattern matching can also be used with tuples to extract values from them. Here's an example:

let point = (x: 10, y: 20)

switch point {
case (let x, let y) where x == y:
    print("Equal x and y values")
case (let x, let y) where x < y:
    print("x is less than y")
    print("Unknown case")

In this example, we match the tuple structure and define conditions based on the values of its elements.