Merge Dictionaries in Swift

This tutorial is all about merging dictionaries in Swift. As the title says merging dictionaries means we need to join or concatenate two dictionaries.

Dictionary is a collection of key-value pairs and combining them is the concept of merging two dictionaries.

There are two methods of merging in Swift namely-

  1. merge()
  2. merging()

Merge two dictionaries using merge() method-

We can merge two dictionaries in Swift using merge(). This functions to join two dictionaries by updating one dictionary and concatenating the elements of the other dictionary.

The implementation part is as follows-

var dict1 = ["Khushi" : 7, "Aswani" : 5]
var dict2 = ["Tina" : 5, "Aswani" : 8]

dict1.merge(dict2){(first, _) in first}

print(dict1)

This example shows that there is a common element in both dictionaries but has some different values. The above code will result in the element from the first dictionary as-

Output-["Tina": 5, "Aswani": 5, "Khushi": 7]
But if we want the element and its value from the second dictionary. The snippet part would change into-
var dict1 = ["Khushi" : 7, "Aswani" : 5]
var dict2 = ["Tina" : 5, "Aswani" : 8]

dict1.merge(dict2){(_, second) in second}

print(dict1)
Output-["Khushi": 7, "Aswani": 8, "Tina": 5]

This is how we can modify and get the output as per our expectations.

Merge dictionaries with the help of merging()

As we have the idea of the merge() method in Swift, there is another method merging() in Swift that does not update the existing dictionaries but creates another dictionary to store the results of both of the above dictionaries.

It is implemented as follows-

var dict1 = ["Khushi" : 7, "Aswani" : 5]
var dict2 = ["Tina" : 5, "Aswani" : 8]

let updateddict=dict1.merging(dict2){(first, _) in first}

print(updateddict)

print(dict1)

This code declares two dictionaries as above and then concatenates the two but as in the above merge() concept, it concatenates it with the first dictionary but here it does not, it is updated on the new dictionary with no changes in any of the dictionary.

Here is the implementation part-

var dict1 = ["Khushi" : 7, "Aswani" : 5]
var dict2 = ["Tina" : 5, "Aswani" : 8]

let updateddict=dict1.merging(dict2){(first, _) in first}

print(updateddict)

print(dict1)
Output-
["Tina": 5, "Khushi": 7, "Aswani": 5]
["Khushi": 7, "Aswani": 5]

Similarly as in the above case, if we want the elements from the second dictionary the above concept will be used with the merging() method and we will get our desired output.

I hope this tutorial was helpful in your task to merge dictionaries in Swift. Thanks for reading!

Also read: Merge two arrays with unique values in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *