Lesson 26Collections
Dictionary Operations
Advanced Dictionary Operations
Now that you know dictionary basics, let's explore powerful operations for modifying and transforming dictionaries!
Modifying Dictionaries
dict[key] = valueAdd or update value
updateValue(_:forKey:)Update and return old value
dict[key] = nilRemove by key
removeValue(forKey:)Remove and return value
Merging Dictionaries
Use merge(_:uniquingKeysWith:) to combine dictionaries. The closure decides which value to keep when keys conflict!
Useful Properties
.keysAll keys
.valuesAll values
.countNumber of pairs
Default Values
Use dict[key, default: value] to get a default value when the key doesn't exist!
main.swift
// Creating and modifying dictionaries
var scores: [String: Int] = ["Alice": 95, "Bob": 87]
// Adding new key-value pairs
scores["Charlie"] = 92
print(scores) // ["Alice": 95, "Bob": 87, "Charlie": 92]
// Updating values
scores["Bob"] = 90 // Direct update
let oldScore = scores.updateValue(88, forKey: "Alice")
print("Old score: \(oldScore ?? 0)") // 95
// Removing key-value pairs
scores["Charlie"] = nil // Remove by setting nil
let removed = scores.removeValue(forKey: "Bob")
print("Removed: \(removed ?? 0)") // 90
// Merging dictionaries
var dict1 = ["a": 1, "b": 2]
let dict2 = ["b": 3, "c": 4]
// Merge with closure for conflicts
dict1.merge(dict2) { current, new in new }
print(dict1) // ["a": 1, "b": 3, "c": 4]
// Get all keys and values
let keys = Array(scores.keys)
let values = Array(scores.values)
// Check if key exists
if scores["Alice"] != nil {
print("Alice has a score!")
}
// Default value for missing keys
let davidScore = scores["David", default: 0]
print("David's score: \(davidScore)") // 0
// Count and isEmpty
print("Count: \(scores.count)")
print("Is empty: \(scores.isEmpty)")
// Filter dictionary
let highScores = scores.filter { $0.value >= 90 }
print(highScores)
// Map values (returns array of tuples)
let doubled = scores.mapValues { $0 * 2 }
print(doubled)Try It Yourself!
Create a dictionary of student grades, then merge it with a new set of grades. Use filter to find all students with A grades (90+)!