Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 146 ยท Control Flow

switch

Master Swift's switch statement and switch expressions - matching values, ranges, tuples, enums and optionals, value bindings, where clauses, fallthrough and compiler-checked exhaustiveness.

If if asks a yes-or-no question, switch asks "which of these is it?". You give it a value and a list of cases, and it runs the first case that matches. In many languages that is where the resemblance to Swift ends: Swift's switch is far more powerful than the C version. It matches ranges, tuples, enum cases with their data, optionals and arbitrary conditions, it never falls through by accident, and the compiler checks that you covered every possibility.

This lesson goes from the basics to value bindings, where clauses and switch expressions (Swift 5.9). It builds on if and else, and the topic continues in Pattern Matching and Enumerations.

The basic switch

Each case lists one or more patterns followed by a colon and the code to run. The default case catches everything else. Unlike C, there is no implicit fall-through: when a case finishes, the whole switch ends, so you never write break at the end of each case.

Swift A first switch

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.

A case can list several values separated by commas (case 3, 4, 5), and switch works on strings, characters, integers, enums, tuples and many other types. The cases are tested from top to bottom and the first match wins, so the order matters whenever patterns overlap.

Every case body must contain at least one statement. To say "do nothing" on purpose, write break:

Swift An explicit empty 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.

Exhaustiveness: the compiler checks every case

A switch must handle every possible value of the type. For an Int that means a default (you cannot list all integers). For an enum it means every case, and the compiler tells you exactly what is missing.

Swift A switch that is not exhaustive (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.

The compiler stops with error: switch must be exhaustive, adds note: add missing case: '.east' and offers to insert it. Add case .east: return .north and it compiles. This is one of Swift's biggest safety features: when you add a new case to an enum later, every switch over it in the whole project fails to compile until you decide what to do. A default case would silence that check, so avoid default when switching over your own enums, and use it for open-ended types such as numbers and strings.

For enums from libraries that might gain cases in the future, Swift uses @unknown default, which handles new cases but still warns you when a known case is missing. You will see it in code that switches over framework enums.

Ranges and intervals

A pattern can be a range (Ranges), which is a clean replacement for chains of if x >= a && x < b:

Swift Switching over ranges

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.

Closed ranges (90...100) include both ends, half-open ranges (80..<90) exclude the upper one, and one-sided ranges (..<0) have no lower limit. Ranges work with Double as well as Int. Because a default is still required, the invalid scores 101 and -1 land safely in the last case.

Tuples and the wildcard

You can switch over several values at once by putting them in a tuple (Tuples). In a pattern, the underscore _ is a wildcard that matches anything and ignores it, so you can say "I don't care about this part".

Swift Matching tuples

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 order is again essential: the specific (0, 0) comes before (_, 0), which comes before the broad ranges. The last default covers the one remaining quadrant. Tuples let you express "if both conditions" in a single, readable table. A classic example is FizzBuzz: switch (n % 3, n % 5) with the cases (0, 0), (0, _), (_, 0) is shorter and clearer than nested if.

Value binding

A case can bind part of the matched value to a name that is then available in the case's body. Use let (or var) in the pattern:

Swift Binding values in cases

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 switch has no default, because the last case let (x, y) matches every tuple of two integers. That is how the compiler sees the switch as exhaustive. Note case let (x, y) is shorthand for case (let x, let y), and the binding can be combined with a range, as the last example shows.

where clauses

A where clause adds an extra boolean condition to a case. It is evaluated after the pattern matches and can use the bound names.

Swift Extra conditions with where

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.

Use where when the test depends on a relation between values, such as x == y, that a plain pattern cannot express. If you have ten where cases in a row, a chain of if statements might be clearer.

Enums with associated values

switch and enums are made for each other. An enum case can carry data, and the pattern extracts it. Enums get a full lesson in Enumerations; this is the essential idea.

Swift Switching over an enum 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.

There is no default, so if someone adds case ellipse(...) later, area(of:) stops compiling and points to the exact place that needs attention. That is the practical benefit of exhaustive switching.

Optionals in a switch

An optional is itself an enum with two cases, .none and .some. In a pattern you can write nil for the first and value? for the second (the question mark after a binding means "unwrap and bind it"):

Swift Switching over optionals

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.

For a single optional, if let is shorter. The switch form shines when you must distinguish between several states of the wrapped value at once, as in the tuple form switch (first, second) over two optionals.

fallthrough

If you really want C-style continuation, write fallthrough. It transfers control into the next case's body without checking its pattern. It is rare, and most uses can be replaced by combining patterns (case 1, 2:).

Swift fallthrough

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 case 2, 3, 5, 7 matches, appends text and falls into the body of case 1, 9, although 3 is not 1 or 9. Notice that it does not continue into default: you must write fallthrough once per hop. You cannot fall through into a case that binds values.

switch as an expression

Like if, a switch can be an expression since Swift 5.9. Each case supplies one expression, and the whole switch has the chosen value. It removes temporary variables and works well with enums.

Swift switch expressions

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.

In isWorkday and shortName, the function body is just a switch expression, so no return is needed. As with if expressions, every case must produce a value of the same type and each branch must be a single expression. When a case needs several statements, use a statement-style switch with return or assign to a var.

Pitfalls and good practice

  • Order of cases. Put specific patterns first. The compiler warns about patterns that can never match when an earlier one already covers them.
  • Avoid default for your own enums, so that new cases are flagged at compile time.
  • Do not forget the type must match: you cannot switch over a Double with case "text".
  • Strings are matched exactly, with ==: "Stop" and "stop" are different. Normalize with lowercased() first.
  • Keep case bodies short. If a case grows beyond a few lines, move it into a function so that the switch stays a readable table.
  • Prefer switch over else if chains when you test the same value for different cases; prefer if when conditions are unrelated.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when a case body in a Swift switch finishes?

    Swift cases do not fall through implicitly. Use the fallthrough keyword if you really want to enter the next case's body.
  2. 2. Why does switching over an enum without default help you?

    Exhaustiveness checking turns a new enum case into compile errors at every switch that must handle it.
  3. 3. Which pattern matches any (x, y) tuple where x is 0, whatever y is?

    The underscore is a wildcard. The tuple pattern (0, _) matches when the first element is 0 and ignores the second.
  4. 4. What does case let n where n > 10: do?

    The pattern let n matches everything and binds the value; the where clause then adds an extra condition.
  5. 5. In the expression let r = switch x { case 1: "one" default: "many" }, what must hold?

    A switch expression produces a value, so every case yields one expression and all must have the same type.

Summary

  • A switch runs the first matching case, has no implicit fall-through and needs no break; fallthrough is explicit.
  • It must be exhaustive: use default for open-ended types, and none (or @unknown default for library enums) for your own enums.
  • Patterns include values, comma-separated lists, ranges, tuples with _ wildcards, enum cases with associated values and optionals.
  • let in a pattern binds part of the value; where adds an extra condition that may use those bindings.
  • Since Swift 5.9, switch can be an expression: one expression per case, all of the same type.
  • Put specific cases before general ones, and keep case bodies short.

Next: Loops