Patternmatching

Introduction to Patterns and Pattern Matching in Swift.

Published on

Swift is a beautiful language, but it hides some powerful features from developers who come from more “old-style” programming languages such as C++ and Java. One such feature is Pattern Matching, and it allows you to write some cleaner code when dealing with some operations.

For example, consider casting. Casting is a feature in the vast majority of statically-typed languages. Casting is considered to be an ugly operation by some, because when you need to cast, it’s usually because the language has a flaw that prevents it from telling you about the right data type underneath. This is specially true when you add in Object-Oriented Programming and classes are marked to return a super type instead of a specific subtype. With pattern matching, you can more cleanly check for datatypes without having to worry about crashes or weird behavior.