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:
(note that Where “where” may be used? is everywhere, pretty much)
(more thoughts on the ? in Matching with Swift’s Optional Pattern)
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!