Dictionaries
A dictionary stores values by key. Looking up a key returns an optional, because the key may be missing.
Optional(5) nil | 2 12 0
Looping
Asha 21 | Meena 19 | Ravi 25 | ["Asha", "Meena", "Ravi"] 65
Dictionaries have no guaranteed order, so sort the keys when you need a stable printout.
Counting and Grouping
[(key: "a", value: 3), (key: "b", value: 1), (key: "n", value: 2)] | [(key: "a", value: ["ant", "ape"]), (key: "b", value: ["bee", "bat"])]
Sets
A set keeps unique values and checks membership very quickly.
[1, 2, 3, 4, 5] [3, 4] [1, 2] | true 3
Choosing a Collection
| Need | Use |
|---|---|
| Ordered list, duplicates allowed | Array |
| Look up by key | Dictionary |
| Unique items or fast contains | Set |
Common Mistakes
- Assuming a dictionary keeps insertion order
- Force unwrapping a dictionary lookup that may be nil
- Using an array when a set would be faster for contains checks
Practice
- Count how many times each word appears in a sentence
- Find the common items of two sets
- Group a list of names by first letter
Conclusion
Use dictionaries for lookups by key and sets for unique values. Remember that lookups return optionals.

