Dictionaries
Prerequisites: Arrays, Unwrapping optionals safely
A dictionary stores key-value pairs: you look up a value by its key instead of by position.
Real-world analogy: a dictionary is a contacts list — you find a phone number by the person's name, not by where it is in the list.
Syntax
var ages = ["Ada": 36, "Linus": 28] // [String: Int]
var empty: [String: Double] = [:]
Reading values
Looking up a key returns an optional, because the key might not exist:
let ages = ["Ada": 36, "Linus": 28]
if let age = ages["Ada"] {
print("Ada is \(age)")
}
print(ages["Grace"] == nil)
print(ages["Grace", default: 0])
print(ages.count)
Ada is 36
true
0
2
ages["Grace", default: 0] returns a plain Int — the default when
the key is missing.
Changing a dictionary
var stock = ["apples": 10, "pears": 4]
stock["plums"] = 7 // add
stock["apples"] = 12 // update
stock["pears"] = nil // remove
stock["apples", default: 0] += 1
for fruit in stock.keys.sorted() {
print("\(fruit): \(stock[fruit, default: 0])")
}
apples: 13
plums: 7
Order is not guaranteed
Dictionaries are unordered — looping over one directly can give the keys in any order, which may change from run to run. Sort the keys (as above) when order matters for output.
let prices = ["tea": 3, "cake": 4]
for (item, price) in prices.sorted(by: { $0.key < $1.key }) {
print("\(item): $\(price)")
}
cake: $4
tea: $3
Common mistakes
- Using a dictionary value without unwrapping it:
ages["Ada"] + 1doesn't compile — the lookup is anInt?. - Expecting the printed order to match the order you wrote.
Practice
Count how many times each word appears in
["red", "blue", "red", "green", "red"] using a dictionary, and print
the counts in alphabetical order.
Show solution
let words = ["red", "blue", "red", "green", "red"]
var counts: [String: Int] = [:]
for word in words {
counts[word, default: 0] += 1
}
for word in counts.keys.sorted() {
print("\(word): \(counts[word, default: 0])")
}
blue: 1
green: 1
red: 3