Dictionaries in Swift are used to store key-value pairs. Each value in a dictionary is associated with a unique key, which allows for efficient retrieval of values based on their corresponding keys. In this tutorial, we will explore how to work with dictionaries in Swift.
To create a dictionary in Swift, you can use the following notation:
var person: [String: Any] = ["name": "John Doe", "age": 30, "isStudent": true]
In the above example, we have created a dictionary
person
with keys "name", "age", and "isStudent" mapping to values "John Doe", 30, and true respectively. The dictionary is of type[String: Any]
, meaning the keys are of typeString
and the values can be of any type.Accessing and Modifying Values
You can access values in a dictionary by providing the key in square brackets:
let name = person["name"] as? String print(name) // Output: Optional("John Doe")
To modify a value in a dictionary, you can simply assign a new value to the key:
person["age"] = 31 print(person) // Output: ["name": "John Doe", "age": 31, "isStudent": true]
Iterating Over a Dictionary
You can iterate over a dictionary using a for loop:
for (key, value) in person { print("Key: \(key), Value: \(value)") }
This will print each key-value pair in the dictionary.
Conclusion
In this tutorial, we covered the basics of working with dictionaries in Swift, including creating, accessing, and modifying values, as well as iterating over a dictionary. Dictionaries are a powerful data structure in Swift that allow for efficient storage and retrieval of key-value pairs.