Articles, podcasts and news about Swift development, 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:

Building Mobile Apps at Scale

Building Mobile Apps at Scale: Based on learnings from scaling the development of the Uber app over four years — this free, 200-page book will help you overcome 39 of the most commonly faced challenges when building large iOS apps. The book is free to download for a limited time, so grab your copy now.