Collections
Swift has three built-in collection types: Array for an ordered list, Dictionary for key-value pairs, and Set for a collection of unique, unordered values. All three are structs, so everything from the previous lesson about copy-on-assignment applies to them too.
Array
Swift main.swift
var scores = [88, 92, 79] scores.append(95) print(scores) print("First: \(scores[0]), Count: \(scores.count)")
Output
[88, 92, 79, 95] First: 88, Count: 4
Dictionary
Swift main.swift
var ages: [String: Int] = ["Priya": 30, "Sam": 25] ages["Jordan"] = 40 if let age = ages["Priya"] { print("Priya is \(age)") } print(ages["Nobody"] as Any)
Output
Priya is 30 nil
Looking up a Dictionary key always returns an optional — ages["Priya"] is a String?, not a plain Int, precisely because the key might not exist. That's exactly the pattern from the optionals lesson showing up in a built-in type.
Set
Swift main.swift
var tags: Set<String> = ["swift", "ios", "swift"] print(tags.count) print(tags.contains("ios"))
Output
2 true
Adding "swift" twice in the literal still leaves only 2 elements — a Set silently drops duplicates and doesn't guarantee any particular order, which is exactly why it's the right tool when uniqueness and fast membership checks matter more than sequence.
Iterating a Dictionary
Swift main.swift
let prices = ["apple": 1.5, "bread": 3.0] for (item, price) in prices.sorted(by: { $0.key < $1.key }) { print("\(item): \(price)") }
Output
apple: 1.5 bread: 3.0
Note: a plain
for (item, price) in prices would work too, but Dictionary iteration order isn't guaranteed to be consistent, so if the order matters for your output, sort explicitly first — as above, with .sorted(by:).