Variables IV
Dictionary
Variables IV
Dictionary
0
0
Checkbox to mark video as read
Mark as read

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)

0 Comments

Join the community to comment

Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy