Swift Optionals are Easy to Understand

Introduction

A Swift optional is a struct that can contain a value or nil. Optionals are useful when the value of a variable is nil and your code expects the variable to contain a value.

Sometimes Swift (via inferred typing) makes a variable an optional. An example is a Dictionary where you have (key: value) pairs and use a key to get its associated value.

Consider the dictionary literal:

let peopleAges = [“William”: 23, “Margaret”: 26, “Nancy”: 30]

You can retrieve Margaret’s age with the statement:

let ageOfMargaret = peopleAges[“Margaret”]

Option clicking on ageOfMargaret presents:

Yes, Swift has made the type of the variable ageOfMargaret to be an Int Optional. This is to protect you from the possibility of the variable ageOfMargaret having no value.

Since ageOfMargaret is an optional, we need to unwrap it to get its value. Consider the statement:

let ageOfMargaretNextYear = ageOfMargaret + 1

I clicked Fix-it and the statement is now

let ageOfMargaretNextYear = ageOfMargaret! + 1

Everything works fine now and the value of ageOfMargaretNext Year is 27.

How Optionals Protect You

Using a key that does not exist, the statement below requests a value.

let ageOfMarge = peopleAges[“Marge”]

Swift (using inferred typing) makes ageOfMarge an Int Optional. Thus, the variable, ageOfMarge, is nil. You can see this by simply typing in the playground:

ageOfMarge

or with the following code:

if let age = ageOfMarge { print(“55”) }
else { print(“ageOfMarge is nil”) }

Take Aways

  1. Let Swift infer data types whenever possible. Swift will make variables optional when there is the possibility that their value may be nil.
  2. Select variable names and use option-click to see their type. If the variable is an optional, it needs to be unwrapped to retrieve its value.
  3. Optionals are good! If a non-optional does not have a value when your program expects one, your program could crash.
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.