There are two ways to add new key values to a given dictionary in Swift. Let’s explore them in this concise example-based article.
Using the subscript syntax
You can use the subscript syntax to add a new key-value pair to a dictionary:
// this dictionary stores the products and their prices
var products = [String: Int]()
products["computer"] = 1000
products["mouse"] = 25
print(products)
Output:
["computer": 1000, "mouse": 25]
If you use the subscript syntax with a key that already exists, its value will be updated.
Using the updateValue(_:forKey:) method
The name of this method contains the word “update,” but it can still be used to add a new key-value pair to a dictionary. The method returns the old value if the key exists or nil
if a new key-value pair is added.
Example:
var animals = ["cat": "meow", "dog": "woof"]
if let oldValue = animals.updateValue("moo", forKey: "cow") {
print("The old value of \(oldValue) was replaced with a new one.")
} else {
print("A new key-value pair was added to the dictionary.")
print(animals)
}
Output:
A new key-value pair was added to the dictionary.
["cat": "meow", "cow": "moo", "dog": "woof"]