Weekly Swift articles, podcasts and tips by John Sundell.

Using key paths in switch statements

Published on 23 Oct 2019

One of Swift’s lesser known, but incredibly powerful language features is how the ~= operator lets us implement custom pattern matching variants between different types. Those new pattern matching capabilities can then be used in switch statements, when using if case syntax, or within any other context in which pattern matching is supported.

Here’s how we could use that language feature to define a ~= overload that matches a boolean key path into a type against an instance of that type:

func ~=<T>(lhs: KeyPath<T, Bool>, rhs: T) -> Bool {
    rhs[keyPath: lhs]

With the above in place, we can now simply use a key path to define a pattern, and mix those patterns freely with those that match against a value — which is really useful when using a switch statement to decide how to parse or handle a given value:

func handle(_ character: Character) {
    switch character {
    case "<":
    case "#":
    case \.isNumber:
    case \.isNewline:

Support Swift by Sundell by checking out this sponsor:

Magic Lasso Adblock
Magic Lasso Adblock

Magic Lasso Adblock: Block ads, trackers and pop-ups on your iPhone, iPad and Mac. Magic Lasso Adblock provides a 2.0x speed increase on common websites, improves your privacy by removing ad trackers and works with Safari across all devices. It’s as if Apple themselves had designed an ad blocker. Download for free today.