Dictionary.updateValue() / Removing Entries / mapValues()
Swift dictionaries provide methods for updating, removing, and transforming elements. updateValue(_:forKey:) returns the old value before the update, making it easy to detect changes.
Method List
| Method | Description |
|---|---|
| updateValue(_:forKey:) | Updates the value for the specified key and returns the previous value as an Optional. |
| removeValue(forKey:) | Removes the key-value pair for the specified key and returns the removed value as an Optional. |
| dictionary[key] = nil | Removes the key-value pair for the specified key (shorthand for removeValue). |
| removeAll() | Removes all elements from the dictionary. |
| mapValues(_:) | Transforms all values and returns a new dictionary. |
| filter(_:) | Returns a dictionary containing only the pairs that match the condition. |
| merge(_:uniquingKeysWith:) | Merges another dictionary into the current one. |
Sample Code
var scores: [String: Int] = ["Alice": 80, "Bob": 70, "Carol": 90]
// updateValue: returns the previous value before updating
if let oldValue = scores.updateValue(85, forKey: "Bob") {
print("Bob のスコアを \(oldValue) から \(scores["Bob"]!) に更新しました")
}
// Returns nil if the key does not exist yet
let result = scores.updateValue(75, forKey: "Dave")
print("Dave は新規追加: \(result == nil)")
// removeValue: returns the removed value
if let removed = scores.removeValue(forKey: "Carol") {
print("Carol(\(removed)点)を削除しました")
}
// Remove a key by assigning nil via subscript
scores["Dave"] = nil
print("削除後: \(scores)")
// mapValues: transform all values
var doubled = scores.mapValues { $0 * 2 }
print("2倍: \(doubled)")
// filter: keep only pairs that match the condition
let highScores = scores.filter { $0.value >= 80 }
print("80点以上: \(highScores)")
// merge: merge dictionaries (duplicate keys are overwritten by the new value)
var extra: [String: Int] = ["Eve": 95, "Alice": 88]
scores.merge(extra) { _, new in new }
print("マージ後: \(scores)")
Overview
updateValue(_:forKey:) lets you update a value and check whether the key already existed at the same time. It returns the previous value as an Optional when updating an existing key, or nil when adding a new key.
mapValues(_:) transforms all values while keeping the keys unchanged. The original dictionary is not modified — a new dictionary is returned instead. The closure passed to merge(_:uniquingKeysWith:) receives two arguments — the existing value and the new value — and returns whichever value should be kept.
For the basics of dictionaries, see Dictionary Basics / dictionary.keys / dictionary.values.
If you find any errors or copyright issues, please contact us.