Dictionaries are a fundamental data structure in Swift that allow you to store key-value pairs. This tutorial will cover how to work with dictionaries in Swift, including declaring, accessing, modifying, and iterating over dictionaries.
In Swift, you can declare a dictionary using the following syntax:
var studentGrades = ["Alice": 95, "Bob": 87, "Charlie": 92]}
This declares a dictionary `studentGrades` with keys "Alice", "Bob", and "Charlie" mapping to their respective integer values.
You can access and modify values in a dictionary using subscript notation:
// Accessing values
let aliceGrade = studentGrades["Alice"]
// Modifying values
studentGrades["Bob"] = 90}
To iterate over a dictionary, you can use a for-in loop with key-value pairs:
for (name, grade) in studentGrades {
print("\(name) has a grade of \(grade)")
}
You can use the `contains` method to check if a key exists in a dictionary:
if studentGrades.contains(where: { $0.key == "Alice" }) {
print("Alice's grade is present in the dictionary")
}
In this tutorial, we covered the basics of working with dictionaries in Swift, including declaring, accessing, modifying, iterating, and checking for key existence. Dictionaries are a powerful tool for mapping keys to values and are commonly used in Swift programming.