if-let Statements

Learn about if-let statements and how they can be used for unwrapping optional values!

if-let Statements

Imagine being a zoo keeper and having a collection of labeled keys that each belong to one of the animal exhibits. The “Giraffe” key leads to the giraffe exhibit, the “Elephant” key leads to the elephant exhibit, and then the “Unicorn” key leads to the…wait. There is no unicorn exhibit in this zoo. It looks like you have a key to something that doesn’t exist. This error could have been avoided if there was a way to check if the exhibit existed before assigning it a key. What you needed was an if-let statement.

An if-let statement is a Swift conditional that is used to unwrap optional values which can then be assigned to variables. While if-let statements have many uses, our main focus will be how to use them to unwrap optionals in a dictionary.

Unwrapping Optionals

First, let’s discuss optional values. In Swift, an optional is a data type that could contain either a value or nil, which means absent of value.

Imagine we had a dictionary that stored the common name of animals as its keys and their scientific name as its values:

var animalNames = [ "Zebra": "Equus quagga", "Giraffe": "Giraffa camalopardalis", "Elephant": "Proboscidea elephantide" ]

If we wanted to assign the value of the key "Giraffe" to a variable called giraffeSci, we could use the following code:

var giraffeSci = animalNames["Giraffe"]

However, when we print() the value of giraffeSci, we get an optional value:

Optional("Giraffa camalopardalis")

Being a type-safe language, Swift returns an optional value as a precaution in case the dictionary doesn’t contain the key we are looking for. By always returning an optional value, we avoid running into errors that occur when we assign a nil optional to a variable.