In this tutorial, we’ll look into Pattern Matching in Swift. Pattern matching is seen in switch statements.

Swift Pattern Matching

The easy to use switch syntax of Swift can be extended to for and if statements as well.
Pattern matching is used to match tuples, arrays, enums etc. or a part of them.

Here’s a very basic example of Pattern matching:

Let’s fire up our XCode Playground and start Swifting.

Partial Matching Tuples

In Switch statements, partial matching is very commonly used and implemented as shown below:

In the above code, we are partially matching only one of the values in the tuple.
Following is the output:

Swift Pattern Matching Tuple Partial Output

 

Swift Pattern Matching Tuple Partial Output

We can write let to each parameter name or like case let as we did in the above snippet.
let is used to bind associated values.

Matching Optionals

Swift has a way of matching optionals.
We can do that by using the .some and .none syntax or just setting a ? on the parameter.

if case let x = y is equal to switch y {case let x: }

The output printed in the console is:

Let’s look at a switch case example for optional matching:

Note: if name and password both are nil, the fourth case would be executed.

Also, instead of some and none, we can use the following syntax as well:

Let’s look at the for case to match optionals.

 

Swift Pattern Matching Optionals Output

where clause is used to set a pattern matching on the optional case.

Matching Types

We can match types in the switch statements as shown below:

~= operator

We can use the ~= operator in the if statements to match a range as shown below:

The ~= operator can be replaced by = or .contains(age) as well but that would cause readability issues.

Pattern Matching With Enums

The last example deals with Pattern matching using Swift Enums.

This brings an end to this tutorial on Pattern Matching in Swift.

By admin

Leave a Reply