← Back to Swift Course | Chapter 6: Collections | Lesson 2 of 7

Dictionaries

A dictionary is like a real dictionary book: you look up a word (the key) to find its meaning (the value).

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

markup
let capitals = ["France": "Paris", "Japan": "Tokyo"]
print(capitals["France"] as Any)
print(capitals["Germany"] as Any)

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

markup
var inventory = ["apples": 10, "bananas": 5]
inventory["oranges"] = 8
inventory["apples"] = 12
print(inventory["apples"]!)
print(inventory["oranges"]!)

Removing Entries

A key-value pair can be removed either by setting its value to nil or by calling removeValue(forKey:).

Example: Removing Entries

markup
var scores = ["Alice": 90, "Bob": 75]
scores["Bob"] = nil
print(scores)
Common Mistakes
  1. Assuming subscript access like dict["key"] always returns the value directly; it actually returns an optional since the key might not exist.
  2. Forgetting that dictionaries in Swift have no guaranteed order -- iterating twice may give different orders.
  3. Overwriting a key's value unintentionally by using the same key twice when building a dictionary literal.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.