Swift – Merge Dictionaries

Welcome to Swift Tutorial. In this tutorial, we will learn how to two dictionaries in Swift programming.

To merge two dictionaries, you can use dictionary.merge method. You may do it in two ways.

  1. Keep the current value (value in dictionary1) if there is a duplicate key
    dictionary1.merge(dictionary2) {(current,_) in current}
  2. Keep the new value (value in dictionary2) if there is a duplicate key
    dictionary1.merge(dictionary2) {(_,new) in new}

The type of keys array is same as that of keyType, and the type of values array is same as that of valueType.

Example 1 – Merge Dictionaries – Keep 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)

Note that as we are merging dictionary2 into dictionary1, the contents of dictionary1 are updated and the contents of dictionary2 are unmodified.

Also, in this example, there is a duplicate key “John” between the two dictionaries. Again, as we are merging dictionary2 into dictionary1, and we used current keyword, the value in the dictionary1 is retained.

Example 2 – Merge Dictionaries – Consider 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)

Note that as we are merging dictionary2 into dictionary1, the contents of dictionary1 are updated and the contents of dictionary2 are unmodified.

Also, in this example, there is a duplicate key “John” between the two dictionaries. Again, as we are merging dictionary2 into dictionary1, and we used new keyword, the value in the dictionary2 is considered.

Conclusion

In this Swift Tutorial, we have learned how to combine or merge two dictionaries in Swift with the help of example programs.