Dictionaries in Swift
What is a Dictionary?
A dictionary in Swift is a collection type that stores key-value pairs. Each key in a dictionary must be unique, and it is used to access its corresponding value. The dictionary is a fundamental data structure for storing related information.
Creating a Dictionary
You can create a dictionary using the following syntax:
This creates an empty dictionary where keys are of type String
and values are of type Int
.
Initializing a Dictionary
Here’s how you can initialize a dictionary with some values:
Accessing Values
You can access the value associated with a specific key using subscript syntax:
The variable aliceAge
will hold the value 30
.
Adding and Updating Values
You can add a new key-value pair or update an existing key's value like this:
ages["Alice"] = 31 // Updates Alice's age
Removing Values
To remove a key-value pair from a dictionary, you can use the removeValue(forKey:)
method:
This will remove Bob from the dictionary.
Iterating Through a Dictionary
You can iterate through the keys and values of a dictionary using a for-in loop:
print("\(name) is \(age) years old")
}
Conclusion
Dictionaries are a powerful way to store and manage data in Swift. They allow for efficient data retrieval based on unique keys. By understanding how to create, manipulate, and access dictionaries, you can effectively manage collections of related information in your applications.