Dictionaries are a fundamental data structure in Swift that allow you to store key-value pairs. In this tutorial, we will explore how to create, modify, and access dictionaries in Swift.
To create a dictionary in Swift, you can use the following syntax:
let myDictionary: [String: Int] = ["apple": 5, "banana": 3, "orange": 7]
In this example, we have created a dictionary where the keys are of type String and the values are of type Int.
You can access and modify the values in a dictionary by using the keys. For example:
myDictionary["apple"] = 10
let numberOfOranges = myDictionary["orange"]
In this code snippet, we are updating the value associated with the key "apple" and then retrieving the value associated with the key "orange".
You can iterate over the key-value pairs in a dictionary using a for-in loop. Here's an example:
for (key, value) in myDictionary {
print("Key: \(key), Value: \(value)")
}
Dictionaries are a powerful data structure in Swift that allow you to store and retrieve key-value pairs efficiently. By understanding how to work with dictionaries, you can build more complex and flexible applications in Swift.