Compleat Pattern Matching

There’s a great series just wrapped up over at Crunchy Development which dives deeper into Swift pattern matching than you’ve ever been, no doubt:

Pattern Matching, Part 1: switch, enums & where clauses

(note that Where “where” may be used? is everywhere, pretty much)

Pattern Matching, Part 2: tuples, ranges & types

Pattern Matching, Part 3: Custom pattern matching & syntactic sugar

(more thoughts on the ? in Matching with Swift’s Optional Pattern)

Pattern Matching, Part 4: if case, guard case, for case

Check out how expressive pattern matching can get by the end of that:

This look might look a little complex, so let’s split it down:

  • It uses map to transform the Array<Media> array mediaList into an array of tuples [(String?, String)] containing the title (if any) + the kind of item (as text)
  • It only matches if title? matches — which is syntactic sugar to say if .Some(title) matches — the $0.title of each media. This means that it discards any media for which $0.title returns nil (a.k.a. Optional.None) — excluding any WebSite in the process, as those don’t have any title)
  • Then it filters the results to only iterate on those for which title.hasPrefix(“Harry Potter”) is true.

Also note particularly in Part 3 about defining the ~= operator for your own types. Which, in case you were wondering,

The pattern matching operator is pronounced “twiddle-eek” not “bacon rocket”. Not only more fun to say but tells you the order in which to type the symbols.

Now you know!


Swift Enumerations

Custom Types for Powerful Matching

Writing Custom Pattern Matching in Swift

Pro Pattern-Matching in Swift

How to use regular expressions in Swift has a String contains matcher — also check out our old regex article

Defining custom patterns in Swift

Alex | May 16, 2016

Leave a Reply