To update the value for a key in a dictionary in Swift, you can use the subscript syntax to assign a new value to the key. If the key does not exist, it will be added to the dictionary with the specified value.
We can update the value for a key in a dictionary in Swift using subscript syntax. This example demonstrates how to update the value for an existing key and add a new key-value pair if the key does not exist.
For example,
myDictionary
with integer keys and string values.var myDictionary: [Int: String] = [
1: "One",
2: "Two",
3: "Three"
]
// Update the value for an existing key
myDictionary[2] = "Two Updated"
// Add a new key-value pair
myDictionary[4] = "Four"
// Print the dictionary contents
print("Dictionary contents:")
for (key, value) in myDictionary {
print("Key: \(key), Value: \(value)")
}
Dictionary contents: Key: 1, Value: One Key: 2, Value: Two Updated Key: 3, Value: Three Key: 4, Value: Four
We can update the value for a key in a dictionary in Swift using the `updateValue(_:forKey:)` method. This example demonstrates how to update the value for an existing key and add a new key-value pair using the `updateValue(_:forKey:)` method.
For example,
myDictionary
with integer keys and string values.var myDictionary: [String: Double] = [
"A": 1.1,
"B": 2.2,
"C": 3.3
]
// Update the value for an existing key
myDictionary.updateValue(2.5, forKey: "B")
// Add a new key-value pair
myDictionary.updateValue(4.4, forKey: "D")
// Print the dictionary contents
print("Dictionary contents:")
for (key, value) in myDictionary {
print("Key: \(key), Value: \(value)")
}
Dictionary contents: Key: A, Value: 1.1 Key: B, Value: 2.5 Key: C, Value: 3.3 Key: D, Value: 4.4
In this tutorial, we learned How to Update the Value for a Key in a Dictionary in Swift language with well detailed examples.