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")
}