Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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

The shortcut

Before storing anything, ask: "Do I get it back by position, by name, or only ask whether it is there?"

Storing TrailLog's dataStep 1 of 4
  1. 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.

quick drill

You need a hike's tags with no duplicates and fast membership checks. Which collection?

quick drill

What is the type of trailByName["Lake Path"] when trailByName is [String: Double]?

quick drill

How many times does for i in 0..<4 run?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainPick the collections

TrailLog needs to store: the list of hikes in the order they were logged; each trail's best time looked up by trail name; and the countries a hiker has visited, counted once each. Choose a collection for each, and write a switch that labels a distance as short (under 5 km), day hike (5 to under 15) or epic.