Optionals in Swift

When to use them and why

John Varghese
The Startup
4 min readJun 1, 2020

--

You are probably aware of the stoptional. The urban dictionary defines it as “any stop sign located in a town with an incredibly small population in which no one is ever around.It is basically a stop sign where most people don’t stop. But if you get caught you would definitely get a ticket for it.

Optionals in Swift are like that. They may or may not have a value depending on the situation. Remember when you programmed in C you had to check if a variable was null? If you did not check for null and if you tried to access the variable when it was indeed null, you would get a null pointer exception. Well, Optionals in Swift make the process of checking for null easier.

How it works

Think of optionals like peanut shells . The kind you can find at Five Guys

When you open them, they usually contain peanuts. But every so often you find that the shell is empty. What do you do with the empty shells? You just throw them away. If you find a peanut or two inside the shell, you eat the peanuts. To know whether there is a peanut inside, you have to unwrap it by opening the shell. It is the same way with optionals. The optional variable actually may or may not contain a value. If it does not contain a value then it will equal nil and you cannot proceed with that variable. You throw it away. If it does contain a value, then you use it and proceed.

To tell the compiler and the programmer that a variable is an optional variable, you follow the variable name with a ?. There are usually only two situations in which the value of the variable will be nil.

  1. When the variable has been declared and not yet assigned a value, then it is nil
  2. When at a later point in the variable’s life it is forcibly assigned a value of nil . Note that only optional variables can ever have a nil value.

How it is better than the old C syntax

In the past you had to remember and explicitly check every time a variable could potentially have a null value. If it could possibly have a null value, you had to write code for that condition or catch the thrown error at a parent level. But with optionals in swift there are two ways you can circumvent this cumbersome process — if let and guard let

  1. With if let you can unwrap the optional. Now if the optional containted a value, the if block will be executed. If not the else block will be executed.
  2. With guard let also you can unwrap the optional. But if the optional does not contain a value, the process will exit the current scope and continue.

There is also a third way to unwrap an optional. By using an ! sign in the variable name in place of the ?. This is called forced unwrapping. You hope that the shell contains at least one peanut. At runtime, if you force unwrap an optional and it contains a value/peanut, then you can use/eat it. But if there is nothing in there (aka nil) then you end up having to eat peanut-shell which contains pesticides and fertilizers that are not good for digestion and you program will instantly crash. I don’t advise forced unwrapping — because that is like not checking for null. There are indeed some corner cases where you can force unwrap — but it is best to avoid them.

When to use Optionals

You can use optionals to represent data that may be missing, unknown, or deleted. For example, let’s say you want to store the number of cherries on a tree in a variable numCherries. If you set it’s initial value to 0 — which is a pretty valid choice in almost all situations, you cannot really tell if you did not count yet or you counted zero cherries on a tree. But if you set it to nil before you count it, then you can know that you have not yet counted (when the value is indeed nil). In normal situations you would have to use another boolean variable to hold that status. You can use nil to represent the absence of a value.

Why use Optionals

The Xcode compiler is very forgiving when you declare a variable as optional. It will help you along as you code reminding you to unwrap the variable before using it. It is such a pleasure to get these hints (in the form of build errors). Once you understand whether your variable should be an optional, then there is no way that a missing value in an optional will cause your program to crash. In other words, it makes programming in swift more fun than it already is.

About John

John runs the Advanced iOS Programming meetup in Cupertino. Due to Covid-19 most of the future meetups will be online, so feel free to sign up. Even if you cannot attend live, you can watch the recordings later (coming soon).

--

--