2.4. Dictionaries
When we hear the word 'dictionary,' we imagine a book of words and their corresponding meanings where we search for the words and find their meanings. Each word has a meaning in a dictionary.
In Swift, a dictionary is a similar data structure to a real-life dictionary. It is a collection of key-value pairs. Where each key is similar to a word in a dictionary book, and the corresponding value is similar to the meaning of the word. A dictionary in Swift has the following properties:
Each element in a dictionary is a pair of a key and a value.
The keys can be of any type.
The values can be of any type.
Once a dictionary is created,
The type for all keys has to be the same.
The type for all values has to be the same.
Creating a dictionary:
We can create an empty dictionary of String-Int pairs by writing the following code:
var carCounts = [String: Int]()Or, you can create a dictionary with predefined key-value pairs, like:
var carCounts = [
"Toyota": 2,
"Mazda": 1,
"Honda":10
]
print(carCounts)It prints:
Adding a new key-value pair and updating a value for a particular key:
For both adding a pair and updating a current value for a particular key, we use updateValue(value, forKey:key) function. The updateValue() function finds if the key already exists or not. If the key is not in the dictionary, it adds the key with the value provided. If the key is found, it just updates the current value with the new value.
For example, we can add 5 more Chevy cars in carCounts by writing:
Alternatively, we can add 5 Chevy cars by writing:
It prints:
Now, if we want to sell one Honda car, we would write:
It prints:
Dictionaries are very useful and very often used in iOS development or any kind of software development.
Accessing a value for a key:
We can fetch how many Mazda cars we have by:
A small challenge: can you try to remove all Honda cars? (Hint: there is a removeValue() function).
Last updated
Was this helpful?