Swift 3 Pattern Matching
Nearly two years ago, Natasha the Robot published a short blog about pattern matching with the if case. While it provided an awesome intro into the if case
, it was just that: an intro.
By the end of this blog, you’ll be able to match & filter circles around your non-case
using colleagues.
The Example
VTS is a commercial real estate technology company — and as such, we’re going to use a building themed example.
In the above example, we have a number of building types with associated values. Enums with associated values can really clean up closely related class
objects — and keep you from making mistakes in your state machines.
Above is effectively the equivalent of Natasha’s example — simple and to the point. It allows us to match enumerations based on a single case, and create a localized variable of the field we’re looking to work with. It allows us to switch on a single case of the enumeration without using a verbose switch
with default
. We can also have conditional matching based on internal fields:
Because we can use if case let
, we can also use guard case let
in a similar way. But, most importantly, we can combine this with a for
loop:
Combining it with a for
loop in this way allows us to filter and match over a collection. This lets us perform powerful filtering techniques in an easy-to-read fashion.
Further Reading
Match Me If You Can, by AppVenture
Pattern Match Operator, Swift Documentation
Swift Pattern Matching, Ole Begemann
For more content, follow me on Medium or on Twitter @_hsalman