Dictionaries
Creating and Accessing a Dictionary
A dictionary literal lists key: value pairs in square brackets, and values are looked up by key using subscript syntax, which returns an optional.
Example: Creating and Accessing a Dictionary
let capitals = ["France": "Paris", "Japan": "Tokyo"]
print(capitals["France"] as Any)
print(capitals["Germany"] as Any)
Login to try C/C++/Java/PHP code in the editor
Adding and Updating Entries
Assigning to a dictionary's subscript adds a new key-value pair or updates an existing one.
Example: Adding and Updating Entries
var inventory = ["apples": 10, "bananas": 5]
inventory["oranges"] = 8
inventory["apples"] = 12
print(inventory["apples"]!)
print(inventory["oranges"]!)
Login to try C/C++/Java/PHP code in the editor
Removing Entries
A key-value pair can be removed either by setting its value to nil or by calling removeValue(forKey:).
Example: Removing Entries
var scores = ["Alice": 90, "Bob": 75]
scores["Bob"] = nil
print(scores)
Login to try C/C++/Java/PHP code in the editor
- Assuming subscript access like
dict["key"]always returns the value directly; it actually returns an optional since the key might not exist. - Forgetting that dictionaries in Swift have no guaranteed order -- iterating twice may give different orders.
- Overwriting a key's value unintentionally by using the same key twice when building a dictionary literal.
- A dictionary maps keys to values, written as
[KeyType: ValueType]. - Subscripting a dictionary (
dict[key]) always returns an optional, since the key might be missing. .updateValue(),removeValue(forKey:), and direct subscript assignment modify a dictionary.- Dictionaries are unordered -- do not rely on insertion order when iterating.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: