Using Dictionaries
When you first start out, you’ll be using lots of arrays, but the dictionary is another collection that is also quite useful. Whereas an array retrieve values based on an index, dictionaries work using key value pairs.
You can think of a dictionary collection much like a regular dictionary. To find the meaning of word, you look up the definition based on the word itself. In the physical dictionary, words are listed in alphabetical order. With a Swift dictionary, you don’t to word about how it is organized. You simply provide the key and the dictionary returns a value.
Swift dictionaries also allow you to define the types of the keys and the values. For instance, you may create a baseball dictionary. This dictionary stores player names by their number. For example, if you had a Dodgers dictionary, you’d pass in the number 42 as the key, and receive Jackie Robinson as the value.
Creating a Dictionary
Creating a dictionary looks a little strange, but like all things with code, you’ll get used to it in time. Here’s a dictionary that uses Strings for both the key and the value.
var animalNames: [String: String] = [:]
You can break down the code in three distinct parts.
var animalNames:
First, you assign a name to the variable. In this case, it’s called animalNames. The colon after the name indicates you’ll be providing the type.
[String: String]
This defines the key and value types of the dictionary. These are both String types, but you can use any valid Swift type.
= [:]
This last bit of code creates an empty dictionary. It looks strange but you can image a key being on the left of the colon and a value on the right of the colon.
You can also use inferred typing as well. When you are using inferred typing, you must provide at least one key and value.
var animalNames = [ "🐕": "Dog"]
Reading Values
Once you have a dictionary created in code, it’s just a matter of getting in setting values. To simply get the value, you pass in the key to the dictionary.
print(animalNames["🐕"]) // prints Dog
By passing in your key, you receive your value. This does pose a problem. Consider the case where a key does not exist. For example:
print(animalNames["🐍"]) // prints nil
Because there wasn’t a snake in the animals dictionary, the returned value is nil. This value means nothing. A nil value can be a dangerous value in your program. It can cause cascading issues in program. For this reason, Swift has created the optional type.
An optional declares that a variable may or may not contain a value. If a variable is an optional, you must “unwrap” the value to access it. Here is an example of unwrapping the snake code:
var name: String? = animalNames["🐍"]
if let name {
print(name)
}
This code declares the name variable as a String optional. It does this with the question mark after the type. The code then unwraps the optional to access the value. If the value were nil, the print statement would be skipped over.
You won’t be working with optionals much in this course, but they are an important part of the Swift language.
Setting Values
You can also easily set values for existing dictionaries. As with all variables, you must be aware of the type names. In the case of the snake, you can simply set the key and the values. For example:
animalNames["🐍"] = "Snake"
Mind you, even though you just added the snake to the dictionary, it will still be returned as an optional. You need to unwrap the value before using it.