Leave a rating/review
Notes: 28. Creating & Populating Dictionaries
Apple’s Swift Dictionary documentation: https://developer.apple.com/documentation/swift/dictionary
Update Notes: The student materials have been reviewed and are updated as of October 2021.
You’re ready to learn about another extremely useful collection type in Swift: dictionaries.
A dictionary is an unordered collection of pairs, where each pair is composed of a key and a value. They’re useful when you want to look up values by means of an identifier. For example, here we have a dictionary where the keys are names of animals, and the values are images of cute animal icons.
Keys in dictionaries must be unique. The same key can’t appear twice in a dictionary - so we couldn’t have two entries for Cat for example.
However, different keys may point to the same value. For example, if we had one for amphibian, it could point to the frog icon.
Also, all of the keys in the dictionary must be of the same type - for example strings here, and all of the values must be of the same type - for example images here.
How is this different from an array? With an array, you can only fetch a value by its index. The index must be an integer, and all indexes must be sequential. With a dictionary, the keys can be of any type and in no particular order. Let’s try using dictionaries in Swift.
You can create an empty dictionary, just like you can create an empty array. The only difference is the syntax. You need to specify the types for both the keys and the values, with a colon right after the key type. And to create an empty dictionary, just put a colon right between a pair of square brackets.
var emptyDictionary: [String: Int] = [:]
Also, like with an array, if you create an empty dictionary the type annotation is required. There’s not enough information for the compiler to infer the type.
But if you make a dictionary and add values right away, type inference will work.
- For example, let’s make a namesAndPets dictionary and add Ron and his pet Rat to it.
var namesAndPets = ["Ron": "🐀 Rat"]
-
Now the compiler can figure out that we want a dictionary with Strings for keys and Strings for the values, too.
-
I’ll fill in this dictionary to store some characters and the type of pet they carry around. I’m using emoji here, with the Control-Command-Space keyboard shortcut, but that can be hard to type so you don’t have to. It’s just for fun.
var namesAndPets = ["Ron": "🐀 Rat", "Rincewind": "🛄 Luggage", "Thor": "🔨 Hammer", "Goku": "☁️ Flying Nimbus"]
- Now try printing out the whole dictionary just to see what that looks like in the console.
print(namesAndPets)
- It looks exactly like the declaration of the dictionary keys and values!
If you have an existing dictionary, and you want to add key value pairs to that dictionary, it’s easy to do so. Like many things in Swift, there’s more than one way to accomplish things, and dictionaries are no exception.
I’ll add myself, Chris, in here, and I’ll add my pet dog, Mango! To do that, I can use the updateValue method on the namesAndPets dictionary, like this:
namesAndPets.updateValue("🐶 Mango", forKey: "Chris")
I provide the name of the value I want to update or add, Mango and the name of the key to add it under, Chris.
It might sound strange to use “update”Value to add a value, but this is actually an efficiency you’ll see a lot in Swift. Instead of having an addValue method, in addition to an updateValue method, you can just simply call the updateValue method.
This way, you don’t have figure out the correct method to call. Swift figures out whether to add it or update it, and the end result is the same.
There’s also a shorthand method to add values to a dictionary, which I prefer. Calvin has a pet tiger. Let’s add them to our dictionary with this shorthand way of doing things. I put the name of the dictionary, specify the key in square brackets, and then set that equal to the value I want to add.
namesAndPets["Calvin"] = "🐯 Tiger"
It’s very much the same way you add elements to arrays, which is why I like it so much.
Modifying or updating a dictionary is nearly the same thing as or update a mutable dictionary, you’ve got some options! Ron eventually lost his pet rat, because it turned out to be a mass murderer in disguise. But after that he got an owl!
I can update Ron’s pet with the updateValue method:
namesAndPets.updateValue("Owl", forKey: "Ron")
It’s the same syntax as adding a key. Nice! Oh, wait, I forgot to add in the Owl emoji. That’s OK though, I can use the shorthand method to update Ron’s pet with a wise old owl emoji:
namesAndPets["Ron"] = "🦉 Owl"
Let me inspect the new dictionary using the sidebar, and I can see that Ron’s entry has been updated properly.
That’s the end of this video: Up next, I’ll show you a few more ways you can modify dictionaries, and how to iterate over dictionaries just like you did with arrays. I’ll see you there!