Dictionaries and Sets
Key-value storage with Dictionary, and unique unordered collections with Set.
2 min read
Arrays keep values in order and allow duplicates. Swift's other two core collections cover the cases where order doesn't matter or uniqueness does: Dictionary and Set.
Dictionary: key-value pairs
var ages: [String: Int] = [
"Ada": 36,
"Grace": 85
]
ages["Sam"] = 42 // add a new entry
ages["Ada"] = 37 // update an existing entry
let adaAge = ages["Ada"] // Int? — 37, wrapped as an optional
let unknown = ages["Zoe"] // nil — "Zoe" isn't a keyEvery lookup by key returns an optional — ages["Zoe"] doesn't crash or return 0; it returns nil, because a missing key is an entirely normal thing to encounter. This is the same pattern you've seen with array's .first and .last: Swift prefers making "this might not exist" explicit over guessing at a placeholder.
let age = ages["Zoe"] ?? 0 // 0 — supply a fallback with nil-coalescingRemoving a key, and iterating over pairs:
ages.removeValue(forKey: "Sam")
for (name, age) in ages {
print("\(name) is \(age)")
}Dictionaries are unordered — the sequence you get from iterating isn't guaranteed to match insertion order, so never rely on it.
Set: unique, unordered values
A Set holds unique values with no guaranteed order — think of it as an array with duplicates automatically eliminated, optimized for fast membership checks.
var tags: Set<String> = ["swift", "ios", "mobile"]
tags.insert("swift") // no effect — "swift" is already present
tags.insert("apple") // added
print(tags.contains("ios")) // true — checking membership is very fast
print(tags.count) // 4.contains() on a Set is dramatically faster than .contains() on an Array for large collections, because a set is backed by a hash table rather than a plain sequential list. If you find yourself repeatedly checking "is this value already in this collection?" and order doesn't matter, a Set is almost always the right choice over an Array.
Set operations
Sets support the mathematical operations their name implies:
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5, 6]
print(a.union(b)) // {1, 2, 3, 4, 5, 6}
print(a.intersection(b)) // {3, 4}
print(a.subtracting(b)) // {1, 2}Choosing the right collection
Reach for Array when order matters and duplicates are fine (a list of steps, a sequence of events). Reach for Dictionary when you need to look values up by a key (a user ID to a user record). Reach for Set when you need uniqueness and fast membership checks, and order doesn't matter at all (a collection of tags, or IDs you've already processed).