Swift Dictionaries
A dictionary is a collection that stores each value under a key. A lookup finds a value by naming its key.
A lookup through if let
The dictionary maps names to scores. The lookup for Ana unwraps to the plain score 90.
var scores: [String: Int] = ["Ana": 90, "Ben": 75]
if let score = scores["Ana"] {
print(score)
}A missing key falls back
The name Ben is not a key here. The lookup gives nil, so ?? prints the fallback 0.
var scores: [String: Int] = ["Ana": 90]
print(scores["Ben"] ?? 0)Adding and changing entries
One assignment adds Ben, and one assignment changes the score for Ana. The count confirms two entries.
var scores: [String: Int] = ["Ana": 90]
scores["Ben"] = 75
scores["Ana"] = 95
print(scores["Ana"] ?? 0)
print(scores["Ben"] ?? 0)
print(scores.count)Removing an entry with nil
Assigning nil to the key Ana removes that entry. The count drops to one.
var scores: [String: Int] = ["Ana": 90, "Ben": 75]
scores["Ana"] = nil
print(scores.count)
print(scores["Ana"] ?? 0)A default inside the lookup
The default spelling answers a missing key directly. The printed 0 is a plain number, not an optional.
var scores: [String: Int] = ["Ana": 90]
print(scores["Ben", default: 0])Example
var stock: [String: Int] = ["pens": 10, "books": 4]
stock["books"] = 6
stock["cards"] = 2
stock["pens"] = nil
print(stock.count)
if let count = stock["books"] {
print(count)
}
print(stock["pens", default: 0])Key points
- Each entry in a dictionary pairs one key with one value.
- The type [String: Int] names a dictionary with string keys and number values.
- Looking up a key gives an optional, because the key may be missing.
- Assigning a value to a new key adds an entry.
- Assigning a value to an existing key changes its entry.
- Assigning nil to a key removes its entry.
- The count property gives the number of entries.
In this example, the first line builds a dictionary with pens at 10 and books at 4. The second line changes the books entry to 6. The third line adds a cards entry at 2. The fourth line removes the pens entry by assigning nil. The fifth line prints the count, which is 2. The if let lookup then prints the books count, 6. The last line prints the default 0 for the removed pens key.
Note
The spelling dict[key, default: 0] gives a plain fallback for a missing key.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
How does a program remove the entry for the key "Ana" from a dictionary named scores?