Learning Swift – Collections [Dictionary]

learning swift collections dictionary

Hello friends,

Now that we have learned arrays and sets, it’s time to finish collections by learning dictionaries. 

Dictionaries. What do you think about when you hear the word dictionary. Well, I think about the dictionaries, the English dictionaries we used when we were kids to find the meaning of words. I use them still. Just that the dictionary is now on the internet. 

 

 

Think about how we used to search a meaning of the word, for example, “rock” in the dictionary. We will straight away go to the r section of the book, then search for a word starting with “ro” and finally zero in on our word rock. Read its meaning and close. 

We wouldn’t start with words starting with a, followed by b, and so on to reach the words starting with “r”. That is going to take a lot of time. Am I right? We will just straight away jump to the words starting with “r”

One important thing to note here is that rock is the key and its meaning is the value. We find the key, we find the meaning.

Just like those English dictionaries, dictionaries in swift are generally pairs/associations of keys and values. These keys and values can be of the same type or different. Also, every value is associated with a key, which is now an identifier for that value.

 


Like sets, dictionaries also have no ordering.

A dictionary is written as [“key” : “value”]

Example, a dictionary of antonyms : [“hot” : “cold”, “dark” : “light”, “big” : “small”]

Here “hot’ will be a key and “cold” its value.

 

 

The swift dictionary type is written using Dictionary[“Key” : “Value”]. This can also be written as [“Key”: “Value”]. The latter form is widely used. 

Coming back to the playground, let’s learn how to initialize and use these dictionaries.

The first method, just like in arrays and sets, uses the initializer syntax.

Here we will use the antonyms example.

 

var antonyms = [String : String]()

 

This will generate variable antonyms which can store keys of type String and values also of type string. Currently, it is initialized as an empty dictionary.

Let’s print this and see

 

print(antonyms)

 

 

This symbol here [:] shows the dictionary is empty.

Now comment this line and the print line and again initialize the dictionary as empty.

 

var antonyms = [:]

 

 

This throws an error “Empty collection literal requires an explicit type”

This happens because the compiler doesn’t know the type of key and values. So we cannot use this way to initialize a dictionary.

When we uncomment our first line. Then remove “var” from this one the error vanishes.

 

 

Let’s add few antonyms to our dictionary. And remove the comment from print statement.

 

antonyms = ["hot" : "cold", "dark" : "light", "big" : "small"]

 

We can see that antonyms now has these values and is not empty.

Moving on to the second method to initialize dictionary using Dictionary Literal. 

Here we will initialize a grocery list dictionary 

 

var groceryList : [String:Int] = ["potatoes" : 4, "carrots" : 6, "onions" : 10]

 

[String: Int] shows that the groceryList is a dictionary with keys of type string and values of type Integer.

There is another point to note here, we don’t need to specify the dictionary type as swift can infer by itself.

 

var groceryList = ["potatoes" : 4, "carrots" : 6, "onions" : 10]

 

Well, now we know how to initialize the dictionary. so let’s have a look at the operations we can perform on it.

The first operation is “Insert”

We use subscript syntax to insert into dictionaries. In this method, we will use a new key having the same type as Keys and assign to it new value having the same type as Values.

Now we will add tomatoes and squash to our dictionary.

 

groceryList["tomatoes"] = 12
groceryList["squash"] = 2

 

See potatoes and squash are added to the dictionary.

Next operation is “Remove”

We will remove squash from our groceryList.

One way is to use subscript syntax and assign the key which we want to delete, a null value. 

 

groceryList["squash"] = nil

 

Now when we print the groceryList and click on the show result, we see that no squash exists in the dictionary.

 

 

Another method is to use removeValue(forKey:) function. For this one let’s remove carrots from our groceryList.

 

groceryList.removeValue(forKey: "carrots")

 

Now when you print the groceryList and click on show result, you can see carrots are removed from the dictionary.

 

 

Next operation is “count” to know the size of our dictionary.

 

print(groceryList.count)

The answer is three as expected.

 

The next and last operation is “Update”.

Let’s print the groceryList once again. You see tomatoes have a value of 12. We will change it to 6.

 

 

Again one way is to use the subscript syntax and assign the new value to a key. 

 

groceryList["tomatoes"] = 6

 

Print the groceryList again. Click on show result button. See the value for tomatoes is now 6.

 

 

Next method is to use updateValue(_:forKey:) function. Let’s change onions to 5 from 10.

 

groceryList.updateValue(5, forKey: "onions")

 

Print the groceryList again. Click on show result button. See the value for onions is now 5.

 

 

This completes our dictionaries and collections. You can find the source code for this post here.