
- Swift Tutorial
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Data Types
- Swift - Variables
- Swift - Optionals
- Swift - Tuples
- Swift - Constants
- Swift - Literals
- Swift - Operators
- Swift - Decision Making
- Swift - Loops
- Swift - Strings
- Swift - Characters
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift - Functions
- Swift - Closures
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift - Initialization
- Swift - Deinitialization
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Type Casting
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift Useful Resources
- Swift - Compile Online
- Swift - Quick Guide
- Swift - Useful Resources
- Swift - Discussion
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.
- Related Articles
- Swift Program to Replace Elements in a Dictionary
- Swift Program to Add Elements to a Dictionary
- Swift Program to Remove duplicate elements from Dictionary
- Swift Program to Sort Elements in Lexicographical Order (Dictionary Order)
- How to append elements to a Pandas series?
- Swift Program to Remove all the elements from Dictionary
- How to convert a JSON string to a dictionary in Swift?
- How to append elements in Python tuple?
- Convert a dictionary to JSON in Swift
- Swift Program to Print a Dictionary
- How to count elements in a nested Python dictionary?
- Swift Program to Search an Element in a Dictionary
- Add elements to a Dictionary in Javascript
- Swift Program to Remove Null from a Dictionary
- Swift Program to Sort a Dictionary By Values
