What is a Dictionary?
A Dictionary is similar to an Array, it's a list of items, but in this case, it's unordered, and we define the index ourselves.
This means that a Dictionary is composed of a list of pairs where one component is the Key, and the other is the Value.
A Dictionary is declared similarly to an Array, but the Key-Value pairs are separated by colons. When specifying the type, we define the type of Key (on the left), and the type of Value (on the right).
var ages: [String: Int] = ["Pablo": 23, "Andrea": 21, "Miguel": 24]
var products: [Int, String] = [2341: "Pants", 33454: "Blouse", 2345: "Socks"]
The advantage of this is storing information and accessing it using "identifiers". For example, linking product IDs with their names.
Adding and Accessing Items
To access an item, you simply use its Key to find it, and since it’s possible that the key might not exist, the result will be an Optional.
print(products[33454]) // Console shows: Optional("Blouse")
To add or edit a value, you do it the same way.
products[33454] = "Shirt"
print(products[33454]) // Console shows: Optional("Shirt")
Removing an Item
The easiest way to remove an item is by using the removeValue(forKey:)
method.
products.removeValue(forKey: 33454)
Be the first to comment