Lesson 25Collections

Dictionaries

Key-Value Pairs

Dictionaries store data as key-value pairs. Each unique key maps to a value, like a real dictionary where words map to definitions!

Dictionary Structure

Key
"name"
Value
"Alice"
Key
"age"
Value
25

Creating Dictionaries

var dict: [String: Int] = ["a": 1, "b": 2]

var empty = [String: String]()

Common Operations

dict[key]

Get value (Optional)

dict[key] = val

Set/update value

dict[key] = nil

Remove key

.keys

All keys

.values

All values

.count

Number of pairs

Access Returns Optional!

Important: dict[key] returns an Optional because the key might not exist!

Use ?? for default: dict["key"] ?? "default"

Or dict["key", default: 0]

When to Use Dictionaries

👤

User Profiles

["name": "...", "email": "..."]

🎮

Game Scores

["player1": 100, "player2": 85]

main.swift
// Creating dictionaries
var person: [String: String] = [
    "name": "Alice",
    "city": "New York",
    "job": "Developer"
]

// Type inference
var scores = ["Alice": 95, "Bob": 87, "Charlie": 92]

// Empty dictionary
var emptyDict: [String: Int] = [:]
var anotherEmpty = [String: Int]()

// Accessing values (returns Optional!)
print(person["name"] ?? "Unknown")  // Alice
print(person["age"] ?? "Not set")   // Not set

// Adding/Updating values
person["age"] = "25"         // Add new key
person["city"] = "Boston"    // Update existing
print(person)

// Removing values
person["job"] = nil          // Remove by setting nil
let removedCity = person.removeValue(forKey: "city")
print("Removed: \(removedCity ?? "Nothing")")

// Dictionary properties
print("Count: \(scores.count)")
print("Is empty: \(scores.isEmpty)")

// Getting all keys and values
let allKeys = Array(scores.keys)
let allValues = Array(scores.values)
print("Keys: \(allKeys)")
print("Values: \(allValues)")

// Iterating through dictionary
for (name, score) in scores {
    print("\(name): \(score) points")
}

// Just keys or values
for name in scores.keys {
    print(name)
}

// Check if key exists
if scores["Alice"] != nil {
    print("Alice has a score!")
}

// Default value if key missing
let davesScore = scores["Dave", default: 0]
print("Dave's score: \(davesScore)")  // 0

// Update with default
scores["Eve", default: 0] += 10
print(scores["Eve"]!)  // 10

Try It Yourself!

Create a dictionary to store contact information (name, phone, email) for yourself. Add a new contact, update your email, and print all the data!