#08: Merging Dictionaries in Swift
Dictionaries do not provide methods for merging with another dictionary generating a new dictionary or to merge in place altering the original object.
But we can add them with a simple extension:
extension Dictionary {
/// Merge and return a new dictionary
func merge(with: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
var copy = self
for (k, v) in with {
// If a key is already present it will be overritten
copy[k] = v
}
return copy
}
/// Merge in-place
mutating func append(with: Dictionary<Key,Value>) {
for (k, v) in with {
// If a key is already present it will be overritten
self[k] = v
}
}
}
Did you like this article? Let me know on Twitter or subscribe for updates!