Introduction to Swift | Control Statements | Multiple Branches with switch

An if statement checks a Boolean condition, so it is suited to choosing between alternatives. A switch statement branches according to a value and can handle many cases.

switch evaluates a value and executes the matching branch.

Basic switch Statement

switch checkedValue {
case value:
    ... processing ...
case value, value ...:
    ... processing ...

default:
    ... processing for other values ...
}

Checked Value

Write the value to check after switch. You can use a literal value, variable, expression, or anything else that evaluates to a value. Parentheses are optional.

The checked value can be a number, text value, or Boolean value.

case

Write a value after case. When it matches the value checked by switch, that branch is executed. A single case can list multiple values separated by commas.

Many languages require an instruction such as break at the end of a branch. Swift does not. After executing a matching branch, Swift automatically exits the switch statement.

default

The final branch should be default:. It handles values that do not match any case. This branch is optional in many languages, but Swift generally requires a switch statement to cover every possible value.

Specifying Ranges

Listing individual values is inconvenient when a branch covers many values. Use a range operator instead.

minimum ... maximum
minimum ..< maximum

The closed-range operator (...) includes both limits. The half-open range operator (..<) includes the minimum value but excludes the maximum value.

The following example uses ranges in a switch statement.

var x = 300

switch x {
case 0:
    "zero"
case 1...9:
    "1 digit"
case 10...99:
    "2 digits"
case 100...999:
    "3 digits"
default:
    "none"
}

Ranges make it easy to branch according to numeric intervals.