Collections and Control Flow
A hiking journal is a list of hikes, a lookup of trails by name, and a set of tags like "summit" or "waterfall". Swift gives you three collections for exactly those jobs, and a few loops and branches to walk through them.
The rule
Array keeps order, Dictionary finds by key, Set keeps things unique.
var distances: [Double] = [8.5, 12.0, 5.2] // Array
var trailByName: [String: Double] = ["Ridge Loop": 8.5] // Dictionary
var tags: Set<String> = ["summit", "forest"] // Set- Array — ordered, indexed from 0, duplicates allowed.
distances[0]is8.5. An index past the end crashes. - Dictionary — key to value, no order.
trailByName["Ridge Loop"]returnsDouble?, because the key might be missing. - Set — no order, no duplicates, very fast
contains. Inserting"summit"again changes nothing.
Collections declared with let cannot change; use var to append, insert or remove.
To walk them, use for–in, often with a range:
for km in distances { print(km) }
for i in 0..<distances.count { print(i) } // 0, 1, 2 (end excluded)
for n in 1...3 { print(n) } // 1, 2, 3 (end included)To branch, use if or switch. Swift's switch must be exhaustive — every possible value must be handled, often with default — and it does not fall through to the next case:
switch km {
case ..<5: print("Short")
case 5..<15: print("Day hike")
default: print("Epic")
}The shortcut
Before storing anything, ask: "Do I get it back by position, by name, or only ask whether it is there?"
The journal
Hikes are shown newest first and read by position. By position → Array:
[Hike].
The trap: forgetting that 0..<count excludes the end while 0...count includes it. Looping 0...distances.count reads one index too far and crashes.
Drills
Answer fast — trust the rule.
You need a hike's tags with no duplicates and fast membership checks. Which collection?
What is the type of trailByName["Lake Path"] when trailByName is [String: Double]?
How many times does for i in 0..<4 run?
What does Swift's switch require that C's does not?
Remember
- Array keeps order, Dictionary finds by key (and returns an optional), Set keeps things unique.
- Shortcut: by position, by name, or "is it there?" picks the collection.
- Trap:
..<excludes the end,...includes it; an array index out of range crashes.
