Pattern matching for custom types in Swift

Pattern matching in Swift is a technique that allows us to check and de-structure data in a concise way. It's most often seen in switch statements, where it can match against a variety of patterns.

An expression pattern is used in a switch case to represent the value of an expression. The magic behind matching these patterns lies in the ~= operator, which Swift uses under the hood to determine if the pattern matches the value. By default, ~= compares two values of the same type using the == operator, but we can overload it to provide custom behavior.

Let's consider a custom type Circle and demonstrate how to implement custom pattern matching for it.

First, we define a simple Circle struct with a radius.

struct Circle {
    var radius: Double
}

let myCircle = Circle(radius: 5)

Now, let's overload the ~= operator to match a Circle with a specific radius.

func ~= (pattern: Double, value: Circle) -> Bool {
    return value.radius == pattern
}

This overload allows us to use a Double in a switch statement case to match against a Circle's radius.

switch myCircle {
case 5:
    print("Circle with a radius of 5")
case 10:
    print("Circle with a radius of 10")
default:
    print("Circle with a different radius")
}

We can add as many overloads as we need. For example, we can define custom logic to check whether the Circle's radius falls within a specified range.

func ~= (pattern: ClosedRange<Double>, value: Circle) -> Bool {
    return pattern.contains(value.radius)
}

The switch statement can now match myCircle against Double values and ranges, thanks to our custom implementations of the ~= operator.

switch myCircle {
case 0:
    print("Radius is 0, it's a point!")
case 1...10:
    print("Small circle with a radius between 1 and 10")
default:
    print("Circle with a different radius")
}

Custom pattern matching in Swift opens up a lot of possibilities for handling complex types more elegantly. By overloading the ~= operator, we can tailor the pattern matching process to suit our custom types. As with any powerful tool, we should use it wisely to enhance our code without compromising on readability.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Check out our book!

Integrating SwiftUI into UIKit Apps

Integrating SwiftUI intoUIKit Apps

UPDATED FOR iOS 17!

A detailed guide on gradually adopting SwiftUI in UIKit projects.

  • Discover various ways to add SwiftUI views to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with new features such as Swift Charts and Lock Screen widgets
  • Migrate larger parts of your apps to SwiftUI while reusing views and controllers built in UIKit