Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 146 ยท Control Flow

Pattern Matching

Understand every kind of Swift pattern - wildcard, value binding, tuple, enum case, optional, type-casting and expression patterns - and use them in switch, if case, guard case and for case loops.

A pattern describes the shape of a value. Matching a value against a pattern answers two questions at once: "does it have this shape?" and "if so, what are its parts?". You have been using patterns since your first switch: case 90...100, case (0, _) and case .circle(let radius) are all patterns.

This lesson puts names to the different kinds, then shows that patterns are not limited to switch. You can use them in if, guard, while and for as well. The foundations are in switch, Tuples and Optionals; here we bring them together.

The kinds of patterns

Swift has a small family of patterns. Once you know them, every case you read is easy to decode.

Pattern Example Matches
Wildcard _ anything, ignoring it
Identifier let n anything, binding it to n
Value / expression 42, "go", 1...9 values equal to, or inside, the expression
Tuple (0, let y) tuples whose elements match
Enum case .circle(let r) one enum case and its data
Optional let x?, nil an optional that has (or lacks) a value
Type-casting is Int, let s as String values of a given type

The next sections go through them with running code.

Wildcards, bindings and tuples

The wildcard _ ignores a part. An identifier pattern (let name) binds a part to a new constant. A tuple pattern combines them. You can put let or var in front of the whole pattern or in front of individual parts.

Swift Wildcard, binding and tuple patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The last case let (x, y) is irrefutable: it matches every tuple of two integers, so the switch is exhaustive without a default. A pattern that always matches is the only kind allowed on the left of a plain let, which is why let (name, _, city) = record needs no if.

Enum case patterns and associated values

An enum case pattern names the case and, when the case carries data, can bind or match that data. This is where patterns are at their best.

Swift Enum patterns with data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Look at the variety in one switch. .key("q") matches a specific value inside the case. .key(let char) binds the payload. .click(x: 0, y: 0) matches both payload values and .click(let x, let y) binds them. .scroll without parentheses ignores the data entirely, which is allowed when you do not need it. Because .key("q") comes before .key(let char), the special case wins.

if case, guard case and while case

A switch is overkill when you care about only one shape. For that, if case tests a single pattern. Note the order, which is a little unusual: the pattern comes first, then =, then the value.

Swift if case and guard case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

if case can be followed by more conditions after commas, and several case clauses can be mixed with ordinary Boolean tests. guard case keeps the binding alive for the rest of the scope, just like guard let. The loop while case let top? = stack.popLast() is a neat idiom: popLast() returns an optional, and the optional pattern let top? stops the loop when it returns nil.

Writing if case .success = outcome without a binding is fine. For a simple equality test on an enum without payloads you can write if outcome == .quit if the enum is Equatable, but enums with associated values are not Equatable automatically, and if case works regardless.

for case: filtering while you loop

for case combines a loop with a pattern: only elements that match are visited, and the bindings are available in the body. You do not need an if inside the loop.

Swift Filtering with for case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first loop uses a type-casting pattern, let number as Int, to keep only the integers from a heterogeneous array. The second loop shows the optional pattern let value?, a compact alternative to compactMap. The where clause adds an extra condition, and the last loop matches a constant (0) in the first position.

Optional patterns

An optional is an enum with two cases, so patterns for it are really enum patterns with a shorthand: nil for .none and value? for .some(value). They are particularly handy when you inspect two optionals together.

Swift Optional patterns on a pair

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Four combinations of "present or absent" are covered with no nested if let, and the compiler verifies that the five cases are exhaustive. If you delete the last case, it complains.

Type-casting patterns

Two patterns work with types. is Type matches when the value is of that type. let name as Type matches and binds the value converted to that type. They are most useful with Any, AnyObject and class hierarchies; Type Casting explains them in depth.

Swift is and as patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

When you switch over Any, a default is always needed because the set of types is open. Order matters here too: the where n < 0 case must come before the plain Int case, or it could never be reached.

Expression patterns and the ~= operator

The last kind is the expression pattern. When you write case 5, case "go" or case 1...10, Swift evaluates the expression and compares it to the value using the pattern-matching operator ~=. The standard library defines it for equatable values (same as ==), for ranges (membership) and for a few other shapes. Because ~= is an ordinary operator, you can overload it to teach switch new tricks.

Swift Custom patterns with ~=

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first overload makes Even() a pattern that tests parity. The second lets any function from Int to Bool be used directly as a pattern, which turns case greaterThan(100) into a readable condition. The last line calls ~= by hand: it is what case 1...10 does for you.

Custom ~= overloads are powerful but surprising to readers. Keep them small, local to a file, and obvious from their names. For most code a where clause is clearer.

A refutable pattern in the wrong place

A plain let declaration accepts only irrefutable patterns, ones that cannot fail: names, wildcards and tuples of those. A pattern that might not match, such as a constant inside a tuple or an enum case, has no place there. The compiler stops you:

Swift A refutable pattern in let (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Swift reports main.swift:2:9: error: expected pattern, pointing at the 5: a declaration can only introduce names. What should happen if the second element were not 5? A declaration has no way to say, so you move to a construct that can handle failure: if case, guard case or switch.

Swift The fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Choosing the right construct

  • switch when you must handle every shape, or several of them. It is the only one that is checked for exhaustiveness.
  • if case / guard case when exactly one shape matters, and you want to bind its parts. Use guard case to unwrap early and keep the rest of the function flat.
  • for case to filter and unpack at the same time. Prefer it to for ... { if case ... }.
  • while case to drive a loop until a shape stops matching.
  • Plain if with == or a Bool method when no data needs binding.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line correctly tests whether result is .success and binds its value?

    if case takes the pattern first, then =, then the value. The other forms are not valid syntax for matching an enum case with a payload.
  2. 2. What does for case let value? in maybe do for an array of optionals?

    The optional pattern value? matches only .some, so nil elements are skipped and the loop body receives the unwrapped value.
  3. 3. What is the pattern-matching operator that case 1...10 relies on?

    Expression patterns are evaluated with ~=. The standard library provides it for equatable values and ranges, and you can overload it for your own types.
  4. 4. Why is let (a, 5) = pair rejected?

    A let declaration requires a pattern that always matches. A constant inside a tuple can fail to match, so use if case, guard case or switch.
  5. 5. In case (let a?, nil): for a pair of Int optionals, what is matched?

    The pattern a? matches .some and binds the wrapped value, while nil matches .none. Together they match a present first element and an absent second one.

Summary

  • A pattern describes the shape of a value; matching it tests the shape and extracts the parts.
  • The kinds are wildcard _, identifier let x, expression (5, 1...9), tuple, enum case, optional (x?, nil) and type-casting (is, as).
  • switch handles every shape and is checked for exhaustiveness; if case, guard case, while case and for case test or filter by a single pattern.
  • In if case the pattern comes first: if case .success(let v) = result.
  • Expression patterns use the ~= operator, which you can overload, but do so sparingly.
  • Plain let accepts only irrefutable patterns; refutable ones belong in if case, guard case or switch.

Next: Functions