Reading — step 1 of 5
Learn
~1 min readCollections
Dictionary<Key, Value> (or [Key: Value] shorthand) is Swift's hash map:
var ages: [String: Int] = [
"Alice": 30,
"Bob": 25,
]
print(ages["Alice"]) // Optional(30) — subscript returns V?
print(ages["Alice"] ?? 0) // 30
ages["Carol"] = 40 // add
ages.removeValue(forKey: "Bob")
Looking up a missing key returns nil — the subscript type is V?. Use ["key", default: 0] for a default:
let count = ages["Carol", default: 0]
Iterate with destructuring:
for (name, age) in ages {
print("\(name): \(age)")
}
Iteration order is not guaranteed. If you need ordered key-value pairs, use OrderedDictionary from the Swift Collections package.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…