Swift: Enums and Pattern Matching

TL;DR: EnumsAndPatternMatching.playground

The deeper you dig into Swift the more you realize that enums are a central feature of the language. Optionals is what dominates most of the discussion when it comes to Swift and many may be surprised that a property declared as Int? can be expanded to Optional<Int> and cmd-click through that declaration to see that Optional is an enum type. And since it is an enum it has a couple of named values which are .none and .some(Wrapped).

What a new Swift developer learns pretty early on is to use “if let” to unwrap an optional value. What is less common, but may be very common in some code bases, is the pattern matching which can be done to check if an optional has a value without unwrapping it or comparing it to nil. The Gist below shows an example of comparing to nil as well as .none and .some.

Beyond checking if an optional has a value, pattern matching can go much further. Let’s try it out by defining fillings for donuts and various types of donuts and apply a switch statement on initialized values for those donuts.

You will see each type of donut has a count. The last type is a jelly donut which is the only one which has a filling. The function to eat the donuts uses a switch statement which matches based on the given conditions in the where clauses. Instead of the usual switch statements which simply matches on each of the enum values this one actually uses .sugar multiple times with different pattern matching filters.

You may wonder where this would be used. What is becoming common is to create enum types which use the Error protocol so that enum values can be initialized with one of the enum values along with any additional details which may be appropriate for that value. Your app or framework could define domains, codes and error strings which are set with an enum type and when errors are logged or reported they could be filtered by a comprehensive series of pattern matches.

Next: Strings and Paths

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.