Skip to the workspace
Pebellslearn by building
Swift Basics  ›  Lesson

Collections and Control Flow

Swift Basics 12 minArrays keep ordered values, dictionaries look values up by key and sets hold unique values, and for-in loops and exhaustive switch statements walk and branch over them.

ios / Collections and Control Flow

Explore each scene at your own pace.

01 · The rule

The rule

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] is 8.5. An index past the end crashes.
  • Dictionary — key to value, no order. trailByName["Ridge Loop"] returns Double?, 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")
}
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.