How to append elements to a dictionary in Swift?


Swift has various methods to append elements to a dictionary.

We will use the below methods to append elements in a dictionary in the Swift language −

  • Append elements using the updateValue() method

  • Append elements using the subscript syntax.

  • Append elements using the merging() methods.

Using the updateValue() method

The updateValue( :forKey:) method in swift is used for updating the value for an existing key or adding a new key-value combination to an existing dictionary. The method will return nil instead of the key's prior value if the key wasn't previously present in the dictionary, Here is an example −

Example 

import Foundation
var userInfo: [String: Any] = ["firstName": "Alex",
   "school": "St. Primary School",
   "score": 8.8,
   "age": 16]
print("Original User Info: \(userInfo)")

// Adding new key-value pairs
userInfo.updateValue("USA", forKey: "country")
userInfo.updateValue("Murphy", forKey: "lastName")
userInfo.updateValue("Martin Murphy", forKey: "fatherName")
print("Updated User Info: \(userInfo)")

Output

Original User Info: ["firstName": "Alex", "age": 16, "school": "St. Primary School", "score": 8.8]
Updated User Info: ["fatherName": "Martin Murphy", "age": 16, "score": 8.8, "lastName": "Murphy", "firstName": "Alex", "school": "St. Primary School", "country": "USA"]

Using the subscript syntax

Alternatively, you can use the subscript syntax to assign a value to a new or existing key. Here is an example.

Example

import Foundation
var userInfo: [String: Any] = ["firstName": "Alex",
   "school": "St. Primary School",
   "score": 8.8,
   "age": 16]
print("Original User Info: \(userInfo)")

// Adding new key-value pairs
userInfo["country"] = "USA"
userInfo["lastName"] = "Murphy"
userInfo["fatherName"] = "Martin Murphy"
print("Updated User Info: \(userInfo)")

Output

Original User Info: ["age": 16, "school": "St. Primary School", "firstName": "Alex", "score": 8.8]
Updated User Info: ["firstName": "Alex", "fatherName": "Martin Murphy", "country": "USA", "score": 8.8, "age": 16, "school": "St. Primary School", "lastName": "Murphy"]

Using the merging() method

You can also use Dictionary's .merging(_:uniquingKeysWith:) method to append elements to a dictionary.

The merging(_:uniquingKeysWith:) is a method on the Dictionary type in Swift that allows you to merge the contents of one dictionary into another dictionary, and specify how to handle duplicate keys.

The method takes two arguments

  • The first argument is the dictionary that you want to merge into the current dictionary.

  • The second argument is a closure that takes two values for the same key and returns the value that you want to keep.

Example

Here is an example that demonstrates how to use the merging(_:uniquingKeysWith:) method −

import Foundation
var userInfo: [String: Any] = ["firstName": "Alex",
   "school": "St. Primary School",
   "score": 8.8,
   "age": 16]
print("Original User Info: \(userInfo)")
// creating a new dictionary with other info
let otherInfo: [String: Any] = ["country": "USA",
   "lastName": "Murphy",
   "fatherName": "Martin Murphy",
   "pincode": 6783456]
userInfo = userInfo.merging(otherInfo, uniquingKeysWith: { current, _ in
   return current
})
print("Updated User Info: \(userInfo)")

Output

Original User Info: ["school": "St. Primary School", "score": 8.8, "age": 16, "firstName": "Alex"]
Updated User Info: ["firstName": "Alex", "pincode": 6783456, "country": "USA", "lastName": "Murphy", "school": "St. Primary School", "age": 16, "fatherName": "Martin Murphy", "score": 8.8]

If keys already exist, it will combine otherInfo with userInfo and utilize the current value. In order to handle duplicate keys, you can alternatively use the merging( :uniquingKeysWith:) function in a different way, such as by maintaining the current dictionary's value or by combining the values, etc.

Note − This method does not modify the original dictionary, it only returns a new dictionary

Conclusion

There are different methods like updateValue(), merging(), and using subscript syntax. All the methods can be used in different cases.

Most of the time, we use subscript syntax to append elements to a dictionary. In Swift, the dictionary is very powerful to handle duplicate keys. In order to manage the duplicate keys, you can use one of the methods provided in the above examples.

Updated on: 28-Feb-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements