We’ve covered how to manipulate our dictionary and we can certainly print out the entire dictionary, but what if we want to access a single key-value pair?
After all, we shouldn’t have to read through an entire dictionary to find a single definition (or scroll through all of our contacts to find a single phone number).
We can use subscript syntax to access the specific value associated with a key. For example, suppose we had the following dictionary fruitNames
:
var fruitNames = [ "mango": "Mangifera indica", "banana": "Musa paradisicum", "apple": "Pyrus malus" ]
If we wanted to extract the value associated with the key "apple"
and assign it to a new variable called appleScientific
, our code would look like this:
var appleScientific = fruitNames["apple"]
If we tried to print the value of (appleScientific)
, we would get an output of:
Optional("Pyrus malus")
Swift returns an optional. The optional type is used in Swift when a value may not exist. For dictionaries, we might be trying to access a key that doesn’t exist, so as a precaution we first get an optional instead of getting the exact value.
There are two methods for extracting values from optionals.
If we aren’t sure if a key exists within a dictionary, we can use an if
-let
statement:
if let appleScientific = fruitNames["apple"] { print(appleScientific) } else { print("This key does not exist.") }
if
-let
statements are used to check if a real value exists inside of an optional. If the value exists, the optional will be unwrapped and assigned to a variable.
If we are absolutely positive a key exists within a dictionary, we can add !
at the end of the statement like so:
var appleScientific = fruitNames["apple"]!
Using !
forces the compiler to unwrap an optional value and interpret the value as its appropriate data type; however, it should be noted that errors can occur when using !
on a value that does not exist.
To read more about unwrapping optionals, check out Swift’s Language Guide.
Instructions
Assign the value associated with the key "Sunflower"
in the dictionary flowerNames
to a variable called sunflowerScientific
using subscript syntax.
Output the value of sunflowerScientific
using print()
.
Modify your code to unwrap the value of sunflowerScientific
by appending !
to the code written in Instruction 1.
Use an if
-let
statement to assign the value associated with the key "Lily"
to a variable called lilyScientific
.
Inside the body of the if
statement, print()
the following statement:
A lily is referred to as a \(lilyScientific) in the science community.