Swift Dictionaries

A dictionary stores pairs of keys and values. Each key is unique and maps directly to one value. Think of it like a real dictionary: you look up a word (the key) and find its definition (the value). In Swift, both keys and values can be any type.

Creating a Dictionary

Dictionary Literal

let capitals = ["France": "Paris", "Japan": "Tokyo", "India": "Delhi"]
let scores = ["Alice": 95, "Bob": 88, "Carol": 72]

Empty Dictionary

var phonebook: [String: String] = [:]
var inventory: [String: Int] = Dictionary()

Diagram: Dictionary Key-Value Structure

Dictionary: capitals

Key         →   Value
-----------     --------
"France"    →   "Paris"
"Japan"     →   "Tokyo"
"India"     →   "Delhi"

capitals["Japan"] → "Tokyo"

Accessing Values

Dictionary lookups return an optional because the key might not exist.

let capitals = ["France": "Paris", "Japan": "Tokyo"]

if let city = capitals["France"] {
    print("Capital of France: \(city)")
}
// Output: Capital of France: Paris

if let city = capitals["Germany"] {
    print(city)
} else {
    print("Germany not found.")
}
// Output: Germany not found.

Default Value With ??

let capital = capitals["Germany"] ?? "Unknown"
print(capital)   // Output: Unknown

Adding and Updating Entries

var stock = ["Apples": 10, "Bananas": 5]

// Add a new key
stock["Oranges"] = 8
print(stock)   // ["Apples": 10, "Bananas": 5, "Oranges": 8]

// Update an existing key
stock["Apples"] = 20
print(stock)   // ["Apples": 20, "Bananas": 5, "Oranges": 8]

Using updateValue

updateValue sets a new value and returns the old one — useful when you need to know what was there before.

let old = stock.updateValue(25, forKey: "Apples")
print(old ?? "Was nil")   // Output: 20
print(stock["Apples"]!)   // Output: 25

Removing Entries

stock.removeValue(forKey: "Bananas")
print(stock)   // ["Apples": 25, "Oranges": 8]

stock["Oranges"] = nil
print(stock)   // ["Apples": 25]

Dictionary Properties

let ages = ["Alice": 30, "Bob": 25, "Carol": 28]

print(ages.count)     // Output: 3
print(ages.isEmpty)   // Output: false

Iterating Over a Dictionary

Keys and Values Together

for (name, age) in ages {
    print("\(name) is \(age) years old.")
}
// Output (order may vary):
// Alice is 30 years old.
// Bob is 25 years old.
// Carol is 28 years old.

Keys Only

for name in ages.keys {
    print(name)
}

Values Only

for age in ages.values {
    print(age)
}

Sorting a Dictionary

Dictionaries are unordered. To loop in a predictable order, sort the keys first.

let sortedNames = ages.keys.sorted()
for name in sortedNames {
    print("\(name): \(ages[name]!)")
}
// Output (alphabetical order):
// Alice: 30
// Bob: 25
// Carol: 28

Dictionary as a Counter

A common pattern uses a dictionary to count occurrences.

let votes = ["Swift", "Kotlin", "Swift", "Python", "Swift", "Kotlin"]
var tally: [String: Int] = [:]

for vote in votes {
    tally[vote, default: 0] += 1
}

print(tally)
// Output: ["Swift": 3, "Kotlin": 2, "Python": 1]

The [key, default: 0] syntax reads the current count or starts at 0 if the key is new — no optional unwrapping needed.

Nested Dictionaries

Dictionary values can themselves be dictionaries.

var users: [String: [String: String]] = [
    "alice": ["email": "alice@example.com", "role": "admin"],
    "bob":   ["email": "bob@example.com",   "role": "user"]
]

if let role = users["alice"]?["role"] {
    print("Alice's role: \(role)")
}
// Output: Alice's role: admin

Converting Between Dictionaries and Arrays

let grades = ["Math": 90, "Science": 85, "English": 92]

let subjects = Array(grades.keys)
print(subjects)   // ["Math", "Science", "English"] (unordered)

let marks = Array(grades.values)
print(marks)      // [90, 85, 92] (unordered)

Summary

Dictionaries map unique keys to values and return optionals when you look up a key. Use subscript assignment to add or update entries, and set a key to nil or call removeValue to delete one. The [key, default:] shorthand simplifies counting and accumulation patterns.

Leave a Comment

Your email address will not be published. Required fields are marked *