Swift – Merge Dictionaries
To merge two dictionaries in Swift, use the merge(_:uniquingKeysWith:) method when you want to update an existing dictionary. The method requires a closure that decides which value to keep when both dictionaries contain the same key.
You can resolve duplicate keys in two common ways:
- Keep the current value (value in dictionary1) if there is a duplicate key
dictionary1.merge(dictionary2) {(current,_) in current}
- Keep the new value (value in dictionary2) if there is a duplicate key
dictionary1.merge(dictionary2) {(_,new) in new}
The two dictionaries must have compatible key and value types. The duplicate-key closure receives the value already stored in the destination dictionary and the new value supplied by the dictionary being merged.
Swift Dictionary merge() Syntax and Duplicate-Key Closure
The following syntax updates dictionary1 by adding the entries from dictionary2:
dictionary1.merge(dictionary2) { currentValue, newValue in
// Return the value to store for a duplicate key
}
Keys that appear only in dictionary2 are added to dictionary1. For a key found in both dictionaries, the closure must return the value that should remain in the merged dictionary.
Merge Swift Dictionaries and Keep the Current Value
In this example, we merge two dictionaries and if there are any duplicate keys, we shall ignore the new value and keep the existing value.
main.swift
var dictionary1:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
var dictionary2:[String:Int] = ["Surya":91, "John":79, "Saranya":92]
dictionary1.merge(dictionary2){(current, _) in current}
print("dictionary1\n------------")
for (key, value) in dictionary1 {
print("(\(key),\(value))")
}
print("\ndictionary2\n------------")
for (key, value) in dictionary2 {
print("(\(key),\(value))")
}
Output
dictionary1
------------
(John,79)
(Mohan,75)
(Saranya,92)
(Surya,91)
(Raghu,82)
dictionary2
------------
(John,79)
(Saranya,92)
(Surya,91)
Because dictionary2 is merged into dictionary1, only dictionary1 is modified. The contents of dictionary2 remain unchanged.
The key John occurs in both dictionaries. The closure returns current, so the value already stored in dictionary1 is retained.
Merge Swift Dictionaries and Keep the New Value
In this example, we merge two dictionaries and if there are any duplicate keys, we shall consider the new value and update the value.
main.swift
var dictionary1:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
var dictionary2:[String:Int] = ["Surya":91, "John":79, "Saranya":92]
dictionary1.merge(dictionary2){(_, new) in new}
print("dictionary1\n------------")
for (key, value) in dictionary1 {
print("(\(key),\(value))")
}
print("\ndictionary2\n------------")
for (key, value) in dictionary2 {
print("(\(key),\(value))")
}
Output
dictionary1
------------
(Surya,91)
(Mohan,75)
(Raghu,82)
(Saranya,92)
(John,79)
dictionary2
------------
(Surya,91)
(Saranya,92)
(John,79)
Again, dictionary1 is updated while dictionary2 is left unchanged.
For a duplicate key, the closure returns new. This means the value supplied by dictionary2 replaces the value previously stored in dictionary1.
Merge Dictionaries with Different Values for the Same Swift Key
The duplicate-key behavior is easier to see when the two dictionaries contain different values for the same key.
var currentScores = ["John": 79, "Mohan": 75]
let updatedScores = ["John": 88, "Saranya": 92]
currentScores.merge(updatedScores) { current, new in
new
}
print(currentScores["John"]!)
print(currentScores["Saranya"]!)
Output
88
92
The existing value for John is replaced by 88, while the new Saranya entry is added normally.
Combine Swift Dictionary Values Instead of Replacing Them
The closure can calculate a combined value rather than simply choosing the current or new value. For numeric dictionaries, for example, duplicate values can be added together.
var inventory = ["Pen": 10, "Notebook": 4]
let newStock = ["Pen": 5, "Pencil": 8]
inventory.merge(newStock) { current, new in
current + new
}
print(inventory["Pen"]!)
print(inventory["Pencil"]!)
Output
15
8
For the duplicate Pen key, the closure adds the existing quantity and the incoming quantity. The Pencil key is inserted because it was not already present.
Create a New Dictionary with Swift merging()
Use merging(_:uniquingKeysWith:) when you need a new combined dictionary without modifying either original dictionary.
let dictionary1 = ["A": 1, "B": 2]
let dictionary2 = ["B": 20, "C": 3]
let combined = dictionary1.merging(dictionary2) { current, new in
new
}
print(dictionary1)
print(dictionary2)
print(combined)
Here, dictionary1 and dictionary2 are constants and remain unchanged. The merged key-value pairs are stored in combined.
Difference Between Swift merge() and merging()
| Method | Result | Changes the original dictionary |
|---|---|---|
merge(_:uniquingKeysWith:) | Updates the dictionary on which it is called | Yes |
merging(_:uniquingKeysWith:) | Returns a new merged dictionary | No |
Choose merge() when in-place modification is intended. Choose merging() when the original dictionaries must remain available in their existing form.
Swift Dictionary Merge Order and Printed Output
A Swift dictionary is an unordered collection. The order in which key-value pairs appear when a dictionary is printed or iterated is not guaranteed. Therefore, your output may list the same entries in a different order from the examples while still representing the same merged dictionary.
Common Swift Dictionary Merge Errors
- Omitting the duplicate-key closure: Swift needs instructions for resolving keys that occur in both dictionaries.
- Expecting the source dictionary to change:
dictionary1.merge(dictionary2)modifiesdictionary1, notdictionary2. - Using incompatible dictionary types: The dictionaries must use compatible key and value types.
- Depending on iteration order: Do not assume merged dictionary entries will be printed in insertion or alphabetical order.
Swift Dictionary Merging FAQs
How do I merge two dictionaries in Swift?
Call firstDictionary.merge(secondDictionary) and provide a closure that returns the value to keep for duplicate keys.
How do I keep the new value when Swift dictionary keys conflict?
Return the second closure parameter, as in { _, new in new }. The incoming value then replaces the existing value.
How do I keep the existing value during a Swift dictionary merge?
Return the first closure parameter, as in { current, _ in current }.
Can Swift merge dictionary values instead of replacing them?
Yes. The duplicate-key closure can return a calculated value, such as current + new for integers or current + new for arrays that should be concatenated.
How do I merge Swift dictionaries without modifying the originals?
Use merging(_:uniquingKeysWith:). It returns a new dictionary and does not mutate either original dictionary.
Swift Dictionary Merge Editorial QA Checklist
- Confirm that every
merge()example clearly identifies which dictionary is modified. - Verify that duplicate-key examples use different values so the selected conflict rule is visible.
- Do not describe dictionary iteration or printed order as guaranteed.
- Check that examples using
merging()assign its returned dictionary to a new variable. - Ensure the dictionaries in each example have compatible key and value types.
Swift Dictionary Merge Summary
Use merge() to add one dictionary’s entries to an existing dictionary and provide a closure to resolve duplicate keys. Use merging() when you need a new combined dictionary without modifying the originals. In this Swift Tutorial, we have learned how to combine or merge two dictionaries in Swift with the help of example programs.
TutorialKart.com