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")
}
Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Enhance older apps with SwiftUI!$45

A detailed guide on gradually adopting SwiftUI in UIKit projects

Updated for iOS 18 and Xcode 16!

Integrating SwiftUI into UIKit Appsby Natalia Panferova

  • Upgrade your apps with new features like Swift Charts and Widgets
  • Support older iOS versions with effective backward-compatible strategies
  • Seamlessly bridge state and data between UIKit and SwiftUI using the latest APIs

Enhance older apps with SwiftUI!

A detailed guide on gradually adopting SwiftUI in UIKit projects

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

Integrating SwiftUI
into UIKit Apps

by Natalia Panferova

Updated for iOS 18 and Xcode 16!

$45

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.

As someone who has worked extensively with Swift, I've gathered many insights over the years. I've compiled them in my book Swift Gems, which is packed with advanced tips and techniques to help intermediate and advanced Swift developers enhance their coding skills. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice to elevate your Swift development. Grab your copy of Swift Gems and let's explore the advanced techniques together.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35