Swift Switch

Swift Switch Statement

The switch statement evaluates a value and compares it against several possible matching patterns.

It provides an alternative to using long, complex if...else if chains.

In Swift, switch statements are extremely powerful, safe, and versatile.


Basic Switch Syntax

A switch statement consists of multiple case blocks. Swift will execute the block of code matching the first case that evaluates to true.

Every switch statement must be exhaustive, meaning it must cover every possible value. To ensure this, you usually provide a default case at the end.

Switch Example:

let dayOfWeek = 3

switch dayOfWeek { case 1: print("Monday") case 2: print("Tuesday") case 3: print("Wednesday") default: print("Other day") }


No Implicit Fallthrough

In languages like C, you must manually write break at the end of every case, otherwise, the code "falls through" to the next case automatically.

In Swift, switch statements do not fall through by default. As soon as the matching case finishes executing, the entire switch statement completes.

You don't need to write break!


Matching Ranges

One of the most powerful features of Swift's switch is its ability to check against ranges!

Switching on a Range:

let score = 85

switch score { case 0..<50: print("Fail") case 50..<80: print("Pass") case 80...100: print("Excellent") default: print("Invalid score") }


Exercise

Do you need to write a 'break' statement at the end of every case in a Swift switch?