Control Flow and Collections

Article · 2:00

Decisions with if and switch, repetition with loops, and the three collections Swift gives you.

Swift's if needs no parentheses round its condition and always needs braces, even for one line - a rule that exists because of a real security bug in Apple's own code where an unbraced if silently skipped a certificate check.

switch is where Swift differs most from what you may be used to. It must be exhaustive: every possible value has to be covered, or the compiler refuses. There is no fall-through between cases, so no break is needed. And a case can match far more than a constant - it can match a range, a tuple, or a value with a condition attached through where.

For repetition, for ... in iterates anything you can walk: a range, an array, the key-value pairs of a dictionary. while and repeat ... while exist for the cases where the number of iterations is not known in advance.

The three collections are Array, an ordered list that allows duplicates; Dictionary, unordered key-value pairs with fast lookup; and Set, unordered unique values with very fast membership tests. Reach for a Set the moment you find yourself writing array.contains inside a loop - that is an O(n squared) pattern that a Set turns into O(n).

let score = 87

// switch must cover every case, and ranges are allowed.
switch score {
case 90...100:
    print("A")
case 80..<90:
    print("B")
case let n where n < 0:
    print("impossible: \(n)")
default:
    print("C or below")
}

// Array - ordered, duplicates allowed.
var shopping = ["milk", "bread", "milk"]
shopping.append("eggs")

// Dictionary - fast lookup by key. Subscript returns an Optional.
var prices = ["milk": 1.45, "bread": 2.10]
prices["eggs"] = 3.20

// Set - unique, and membership is fast.
let aisles: Set = ["dairy", "bakery", "dairy"]   // two members, not three

for (item, price) in prices.sorted(by: { $0.key < $1.key }) {
    print("\(item): \(price)")
}

print("unique items: \(Set(shopping).count), aisles: \(aisles.count)")