Leave a rating/review
Notes: 29. Accessing & Working with 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.
Hey - welcome back! In the previous video, you learned about how to create dictionaries, how key-value storage works, and how to add and update elements in your dictionary. But there’s a whole lot more to dictionaries than just that!
Dictionaries have many of the same qualities as arrays; you can use their built-in methods to check to see if they’re empty, how many key-value pairs they contain, or if a dictionary contains a a particular value. But unlike arrays, dictionaries are a bit more flexible when you ask a dictionary for something it doesn’t contain.
Remember what happened when you tried to access an array index that didn’t exist? That’s right - the dreaded “Index out of range” error. You always had to be aware of the range of a particular array.
But with dictionaries, all you do is ask it for a key, and if it doesn’t exist, a dictionary simply returns nil. Easy peasy, no error, and no range to keep track of.
Just like arrays, you can iterate over dictionaries with a loop. But instead of just returning the value of the element at a particular index, a dictionary returns the key-value pair inside a tiny collection that you saw earlier in this course - a tuple!
Open up the playground page for this video and let’s get started learning how to access and iterate over dictionaries.
To access a value in a dictionary, you can use the same syntax you used to access values in an array. This time, though, you use a key instead of an index number.
- So to get Rincewind’s pet…
namesAndPets["Rincewind"]
-
You just put “Rincewind” in brackets, like that.
-
Unlike arrays, if you try to get a value for a key that doesn’t exist…
namesAndPets["Captain Ahab"]
-
You get
nilback instead of a fatal error! Captain Ahab isn’t a key in our dictionary, so that’s what we get. -
You can check the result just like you would any
Optional. For example we can use nil coalescing.
let captainAhabPet = namesAndPets["Captain Ahab"] ?? "No white whale for Captain Ahab"
- There’s no “Captain Ahab” in the dictionary, so we get the default value of “No white whale for Captain Ahab” in the sidebar.
Dictionary has a few other properties that should look familiar.
-
You can check if a dictionary is empty with
isEmpty
namesAndPets.isEmpty
- And you can get the count to tell you how many pairs are in a dictionary.
namesAndPets.count
- We’ve got 7!
Removing pairs from dictionary is just as easy as adding them. You can use the removeValue method to remove the value for a specific key. Goku dies several times throughout his life, so if we remove the value for “Goku”…
namesAndPets.removeValue(forKey: "Goku")
It removes the entire pair. What’s interesting is that removeValue returns the value corresponding to the key you just removed, in case you want to do something with that value. You can’t have a key without a value in a dictionary.
-
To prove this, comment that last line out to try the shortcut version.
-
Remember that if you check a key that doesn’t exist, the result is
nil? Try setting the value for “Hiccup” to nil, to see what happens:
namesAndPets["Hiccup"] = nil
- Then print out the dictionary again.
print(namesAndPets)
- You should see that both Goku and Hiccup have been removed.
You can iterate through arrays using for loops, and you can do exactly the same thing with a dictionary! The difference is you need to account for having a key and a value, instead of just a value.
- If you want to use both the key and value inside of the loop, you can name both of them in parenthesis, like this:
for (character, pet) in namesAndPets {
}
- And then just try printing something from inside of the loop, like “character has a pet”.
for (character, pet) in namesAndPets {
print("\(character) has a \(pet)")
}
- In the console, we can see who has what kind of pet!
If you only want to use the key or the value inside of the loop, there are a couple ways to do that. You might have guessed one of them already!
- You can use an underscore in place of the part of the pair you don’t need, just like when you pull values out of a tuple.
for (name, _) in namesAndPets {
print(name)
}
The other option is to specify that you want to iterate through just the keys or the values of the dictionary.
-
Both
keysandvaluesare properties of every dictionary, so Swift makes it easy to iterate over each.
Let me put a little separator in here to separate the output from the last command from what I’m about to do:
print("---")
Now, let me iterate over the pet dictionary, using the .keys property
for pet in namesAndPets.keys {
print(pet)
}
This does the exact same thing as above; it’s just a little more compact and clear. I can also iterate over the values of the dictionary in the same way:
for pet in namesAndPets.values {
print(pet)
}
- Check the console to see the list of names, and then the list of pets!
Just like with arrays, there are more properties and methods available than what I’ve shown you. Stay curious as you continue programming in Swift, and don’t be afraid to try new things — this is how you learn!
That’s it for this video; it’s time to exercise your knowledge of dictionaries in the next video, where I have some challenges for you!