Skip to content
LumenaryAcademy
Foundations 50 min

Control flow and switch

if and guard, loops over ranges and collections, and a switch statement that matches patterns and must cover every case.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Familiar shapes, sharper edges

You already know how to make a program choose and repeat. Swift's control flow will look familiar: if, for, while, break, continue. But each has been reshaped by the same goals as the rest of the language. Conditions must really be Booleans. Braces are always required, even around a single statement, so the famous bug in which an extra indented line silently escapes an if cannot happen. The old C loop for (i = 0; i < n; i++) is gone, removed in Swift 3 because ranges and collections said the same thing more clearly.

And then there is switch, which in Swift is not the jump table you may know from C or Java but a full pattern-matching construct. It can match ranges, tuples and, later in the course, enums carrying data. It never falls through to the next case by accident, and the compiler checks that it covers every possible value. Many experienced Swift programmers would name it as one of the features they miss most in other languages.

DefinitionsH

if, guard, and decisions as values

An if statement needs no parentheses around its condition, but it does need braces:

swift
if temperature > 30 {
    print("Hot")
} else if temperature < 10 {
    print("Cold")
} else {
    print("Pleasant")
}

The condition must be a Bool. Write if count { ... } with an Int and the compiler says type 'Int' cannot be used as a boolean; test for '!= 0' instead. Conditions can be combined with &&, || and !, which short-circuit as in other languages, and a comma between conditions also means "and".

guard: leave early

Definition— guard

A guard statement checks a condition that must be true for the rest of the scope to make sense. If the condition is false, its else block runs, and that block must leave the scope: by return, throw, break, continue, or a call that never returns, such as fatalError.

swift
func averageSpeed(distance: Double, hours: Double) -> Double {
    guard hours > 0 else {
        return 0
    }
    return distance / hours
}

guard keeps the "happy path" of a function at the left margin instead of nesting it deeper and deeper inside if blocks. Its real power appears with optionals in the next lesson, where guard let unwraps a value and keeps it available for the rest of the function.

if and switch as expressions

Since Swift 5.9, if and switch can produce a value directly, when each branch is a single expression:

swift
let label = if score >= 50 { "pass" } else { "try again" }

This replaces the pattern of declaring a variable and assigning it in each branch, and works with let, so the result is a constant. The ternary operator condition ? a : b is still common for very short choices.

Worked examplesH

Loops

for-in walks over anything that is a sequence: a range, a stride, an array, a dictionary, a string's characters. A closed range 1...5 includes both ends; a half-open range 0..<5 stops before 5, which is what you want when counting positions in a collection of 5 elements.

swift
let runners = ["Amara", "Bao", "Carmen", "Dmitri"]
let times = [12.4, 11.9, 12.8, 12.1]

for (place, name) in runners.enumerated() {
    print("\(place + 1). \(name)")
}

for (name, time) in zip(runners, times) where time < 12.5 {
    print("\(name) qualified with \(time) s")
}

for k in stride(from: 10, to: 0, by: -3) {
    print(k, terminator: " ")
}
print()

var total = 0
for n in 1...100 where n % 7 == 0 {
    total += n
}
print("Sum of multiples of 7 up to 100: \(total)")
text
1. Amara
2. Bao
3. Carmen
4. Dmitri
Amara qualified with 12.4 s
Bao qualified with 11.9 s
Dmitri qualified with 12.1 s
10 7 4 1 
Sum of multiples of 7 up to 100: 735
  • enumerated() pairs each element with a counter starting at 0, which is why the program adds 1 for a human-friendly place. (The counter is a count, not an index: for an array slice they differ. To get indices, loop over runners.indices.)
  • zip walks two sequences in step and stops at the end of the shorter one, so it never reads past the end.
  • A where clause filters the loop: the body runs only for elements that satisfy it.
  • stride(from:to:by:) counts by any step, excluding the end; stride(from:through:by:) includes it.
  • print normally ends with a newline; terminator: " " replaces it, and the empty print() finishes the line.

If you don't need the loop variable, write _: for _ in 1...3 { print("knock") }. The loop constant is a fresh let on each iteration; you cannot assign to it.

To loop over a dictionary, write for (key, value) in dict. Remember from the last lesson that the order is unspecified: write for key in dict.keys.sorted() when you need a predictable order.

while, repeat-while and labelled statements

while checks its condition before each pass; repeat { ... } while condition checks after, so its body always runs at least once.

swift
// How many steps does the Collatz process take to reach 1?
func collatzSteps(_ start: Int) -> Int {
    var n = start
    var steps = 0
    while n != 1 {
        n = n % 2 == 0 ? n / 2 : 3 * n + 1
        steps += 1
    }
    return steps
}
print(collatzSteps(6), collatzSteps(27))

// Find the first pair of seats, row by row, whose numbers add up to a target.
let rows = [[3, 8, 1], [6, 4, 9], [2, 7, 5]]
let target = 13
var found: (Int, Int)? = nil
search: for row in rows {
    for a in row {
        for b in row where a < b && a + b == target {
            found = (a, b)
            break search
        }
    }
}
print(found ?? (0, 0))

var attempts = 0
repeat {
    attempts += 1
} while attempts * attempts < 50
print("attempts: \(attempts)")
text
8 111
(4, 9)
attempts: 8

The Collatz rule (halve an even number, triple an odd one and add one) reaches 1 from 6 in 8 steps, and from 27 in 111: nobody has proved it always reaches 1, which makes it a nice reminder that a while loop's termination is your responsibility, not the compiler's.

The seat search shows a labelled statement. A plain break would leave only the innermost loop; break search leaves the loop labelled search: and so all three at once. continue label works the same way. The (Int, Int)? type means "a pair, or nothing yet"; the question mark makes it an optional, the subject of the next lesson, and ?? (0, 0) supplies a value to print if nothing was found.

Worked examplesH

switch: pattern matching

Definition— switch

A switch compares a value against a list of patterns in order and runs the first case that matches. Swift requires the cases to be exhaustive: together they must cover every possible value of the type, or the program does not compile. A case never falls through into the next one.

Patterns can be literal values, several values separated by commas, ranges, tuples, the wildcard _ (matches anything), or value bindings that capture part of the value under a name. A where clause adds an extra condition.

swift
func describe(_ point: (Int, Int)) -> String {
    switch point {
    case (0, 0):
        return "the origin"
    case (_, 0):
        return "on the x-axis"
    case (0, let y):
        return "on the y-axis at \(y)"
    case let (x, y) where x == y:
        return "on the diagonal"
    case let (x, y) where x > 0 && y > 0:
        return "in the first quadrant"
    default:
        return "somewhere else"
    }
}

for p in [(0, 0), (5, 0), (0, -2), (3, 3), (2, 9), (-1, 4)] {
    print(p, "is", describe(p))
}

func grade(_ score: Int) -> String {
    switch score {
    case 90...100: "A"
    case 80..<90: "B"
    case 65..<80: "C"
    case 0..<65: "not yet"
    default: "invalid score"
    }
}
print(grade(93), grade(80), grade(64), grade(120))

let ch: Character = "é"
let kind = switch ch {
case "a", "e", "i", "o", "u": "plain vowel"
case "á", "é", "í", "ó", "ú": "accented vowel"
default: "something else"
}
print(kind)
text
(0, 0) is the origin
(5, 0) is on the x-axis
(0, -2) is on the y-axis at -2
(3, 3) is on the diagonal
(2, 9) is in the first quadrant
(-1, 4) is somewhere else
A B not yet invalid score
accented vowel

Order matters: (0, 0) also matches (_, 0), but the first matching case wins, so the origin gets its own description. The grade function uses switch as an expression: each case is a single value, and the function returns whichever one is chosen (a function whose body is a single expression returns it without return). The last switch is assigned straight to a constant.

Why exhaustive, and why no fall-through?

An Int has about 18 quintillion possible values, and the cases in grade cover only 0 to 100, so the default is required: without it, the compiler reports switch must be exhaustive. That may seem fussy for integers, but the rule earns its keep with enums (lesson 6). When you add a new case to an enum, every switch that forgot to handle it becomes a compile error, so the compiler hands you a list of every place in the program that needs updating.

In C and Java, forgetting a break makes execution fall into the next case, a bug so common that languages added warnings for it. Swift turns the default around: each case ends by itself. If you really want the next case's code to run too, write the keyword fallthrough; you will rarely need it, because one case can list several patterns. Each case must contain at least one statement; write break for a case that deliberately does nothing.

Patterns outside switch

Patterns are not locked inside switch. When you want to test a single pattern, if case does it without the ceremony of a default, and for case runs a loop body only for the elements that match:

swift
let age = 15
if case 13...19 = age {
    print("teenager")
}

let points = [(1, 0), (2, 5), (7, 0)]
for case let (x, 0) in points {
    print("on the x-axis at", x)
}
// prints: teenager, then "on the x-axis at 1" and "on the x-axis at 7"

The if case line reads backwards at first: pattern on the left, value on the right. For a plain range test, (13...19).contains(age) says the same thing more plainly, and most people write that. Range matching works through an operator, ~=, which switch calls behind the scenes; 13...19 ~= age is true here. You can define ~= for your own types to make them usable as patterns, though it is rare to need to. Where if case and for case really shine is with enums that carry values, in lesson 6.

Worked examplesH

Worked example: a robot on a grid

Example— Following commands, skipping bad ones

A delivery robot receives a list of commands, each a direction letter and a number of steps. Some commands are garbage: an unknown direction, or zero steps. We want its final position, a description of where that is, and how many commands were ignored. Everything in this lesson appears: a loop that takes tuples apart, a guard that rejects bad input with continue, a switch on characters, and a switch expression on a tuple with one-sided ranges.

swift
// A delivery robot on a grid follows a list of (direction, steps) commands.
let commands: [(Character, Int)] = [
    ("N", 3), ("E", 2), ("J", 1), ("S", 1), ("W", 5), ("N", 0), ("E", 4),
]

var x = 0
var y = 0
var ignored = 0

for (direction, steps) in commands {
    guard steps > 0 else {
        ignored += 1
        continue
    }
    switch direction {
    case "N": y += steps
    case "S": y -= steps
    case "E": x += steps
    case "W": x -= steps
    default:
        ignored += 1
    }
}

let area = switch (x, y) {
case (0, 0): "home"
case (1..., 1...): "north-east"
case (...(-1), 1...): "north-west"
default: "south or on an axis"
}
print("Final position (\(x), \(y)), \(area); ignored \(ignored) command(s)")
text
Final position (1, 2), north-east; ignored 2 command(s)

Trace it by hand: north 3 puts the robot at (0, 3); east 2 at (2, 3); J is unknown and falls to default; south 1 gives (2, 2); west 5 gives (−3, 2); north 0 is rejected by the guard; east 4 ends at (1, 2). The ranges 1... and ...(-1) are one-sided: "1 or more" and "−1 or less". Note the parentheses in ...(-1), needed so the minus sign is not read as part of the operator.

Two design choices are worth copying. The guard handles the bad case first and gets out of the way, so the switch below it only ever sees sensible step counts. And the description is computed by a switch expression into a let, so there is no variable that might be left unset on some path.

Common misconceptionsH

Common misconceptions

Misconception

"for i in 5...1 counts down." A range must have its lower bound first. This loop does not run backwards; it stops the program with Fatal error: Range requires lowerBound <= upperBound. To count down, write for i in (1...5).reversed() or for i in stride(from: 5, through: 1, by: -1).

Misconception

"for i in 0...array.count visits every index." A closed range includes its upper end, so the last value of i is array.count, one past the last valid index, and the program traps there. Use 0..<array.count, or better, array.indices, or loop over the elements directly.

Misconception

"default is good practice in every switch." For integers and strings it is necessary. For enums, a default turns off the most useful check Swift has: when someone adds a case, your switch silently routes it to default instead of failing to compile. Prefer listing every case of your own enums.

Misconception

"guard is just if with the condition reversed." The difference is the guarantee. A guard must leave the scope when its condition fails, which the compiler checks, so every line after it can rely on the condition. And names unwrapped by guard let remain usable after the guard, which names bound by if let do not.

ExplanationH

How it looks in professional code

Read a mature Swift codebase and you will notice a shape: functions start with a few guard statements that reject bad input, followed by straight-line code at one indentation level. Loops are fewer than you might expect, because many of them become calls such as map, filter and reduce, which you will meet in the lesson on closures. switch appears everywhere enums do, almost always without a default. And labelled statements are rare: when a search needs to escape several loops, many developers move the search into a function and return from it, which says the same thing and gives the search a name.

Exercises

Exercises

1. Control flow and switch

Warm-upComputational

What does this program print?

var s = ""
for i in stride(from: 1, through: 9, by: 3) {
    s += String(i)
}
print(s)

2. Control flow and switch

Warm-upComputational

How many times does the body of this loop run?

for i in 0..<10 where i % 3 == 0 {
    print(i)
}

3. Control flow and switch

CoreComputational

What does this program print?

func label(_ p: (Int, Int)) -> String {
    switch p {
    case (_, 0): "x-axis"
    case (0, _): "y-axis"
    case let (a, b) where a == -b: "anti-diagonal"
    default: "elsewhere"
    }
}
print(label((0, 0)), label((3, -3)), label((0, 4)))

4. Control flow and switch

StretchComputational

What does this program print?

var count = 0
outer: for i in 1...4 {
    for j in 1...4 {
        if j > i { continue outer }
        if i * j > 6 { break outer }
        count += 1
    }
}
print(count)

5. Control flow and switch

CoreComputational

What does this program print?

var n = 100
repeat {
    n /= 3
} while n > 5
print(n)

6. Control flow and switch

CoreHuman

items has 4 elements. What happens when this runs?

for i in 0...items.count {
    print(items[i])
}
Choose one

7. Control flow and switch

CoreHuman

Your team's code has a switch over an enum you own, with a default: case that logs "unexpected". A colleague adds a new case to the enum. What is the main cost of that default?

Choose one

Further reading and resources