To add a key-value pair to a dictionary in Swift, you can use the subscript syntax or the `updateValue(_:forKey:)` method.
We can add a key-value pair to a dictionary in Swift using subscript syntax. This example demonstrates how to add key-value pairs to a dictionary and print its contents.
For example,
myDictionary
.var myDictionary: [Int: String] = [:]
// Add key-value pairs to the dictionary
myDictionary[1] = "One"
myDictionary[2] = "Two"
myDictionary[3] = "Three"
// 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 Key: 3, Value: Three
We can add or update a key-value pair in a dictionary in Swift using the `updateValue(_:forKey:)` method. This example demonstrates how to add or update key-value pairs in a dictionary and print its contents.
For example,
myDictionary
.var myDictionary: [String: Double] = [:]
// Add or update key-value pairs in the dictionary
myDictionary.updateValue(1.1, forKey: "A")
myDictionary.updateValue(2.2, forKey: "B")
myDictionary.updateValue(3.3, forKey: "C")
// 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.2 Key: C, Value: 3.3
In this tutorial, we learned How to Add a Key-Value Pair to a Dictionary in Swift language with well detailed examples.