Dictionary maps keys to values with hash-based lookup—like Map in Java, dict in Python, or objects in JavaScript (with different semantics).
Syntax and access
var scores: [String: Int] = ["Ada": 98, "Lin": 87]
scores["Grace"] = 92
if let ada = scores["Ada"] {
print(ada)
}
Subscript returns optional value—missing keys yield nil, not a crash.
Iteration
for (name, score) in scores.sorted(by: { $0.key < $1.key }) {
print("\(name): \(score)")
}
Important interview questions and answers
- Q: Dictionary key requirements?
A: Keys must conform toHashable—strings, integers, enums often qualify. - Q: Missing key behavior?
A: Subscript returnsValue?—use nil-coalescing orguard letwhen key must exist.
Self-check
- What type is returned by
dict["missing"]? - How do you add or update a key-value pair?
Pitfall: Subscript returns optional—missing keys yield nil, not a crash.
Interview prep
- Missing key?
Subscript returns Value?—nil when absent.
- Key requirements?
Keys must conform to Hashable.