NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Lear more...

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.

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

Check out our new book!

Swift Gems

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

Swift Gems

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

  • 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
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift