Lesson Notes and Walkthrough
A dictionary stores data in key-value pairs. Instead of finding data by index (like arrays), you find it by key. This is useful when each item has a unique identifier.
When to Use a Dictionary
- When you need fast lookup by name, ID, or label.
- When each value belongs to a unique key.
- When order is less important than quick access.
Basic Swift Syntax
var scores: [String: Int] = ["Alex": 90, "Sam": 88] This means keys are String values and stored values are Int.
Step-by-Step Example
var scores: [String: Int] = ["Alex": 90, "Sam": 88]
scores["Alex"] = 95 // update value
let alexScore = scores["Alex"] ?? 0 // safe read
print(alexScore)
print(scores.count) Why ?? Is Important
Looking up a key may return no value. The ?? operator gives a fallback so your app does not crash. Example: scores["Taylor"] ?? 0.
Common Beginner Mistakes
- Assuming every key always exists.
- Using inconsistent key names (for example
"alex"vs"Alex"). - Using a dictionary when ordered data is required.