Optionals

Terry Xu
Swift Basics Series
3 min readOct 12, 2015

--

Swift optionals is an elegant way to represent variables whose values can be ‘nil’. Every program needs to deal with ‘nil’ values, understanding optionals allows us to write code that’s succinct, easy to reason about, and free of runtime errors. However, for people who are used to coding in C, Java, Python, Javascript, Obj-C and other languages which don’t have optionals, it may seem cumbersome and unnecessary to use optionals at first. Instead, people tend to unwrap every optional using ‘!’ which resulted in code that is harder to follow.

In this post, I’d like to illustrate how to use optionals idiomatically.

Setup The Models

The code snippet below sets up class definitions which we will use later on. Notice some properties are defined as optionals. Make sure you know why they should be defined as such.

Chapter 1

If you are learning to program in Swift, chances are you are familiar with Apple’s history. Let’s retell the story of Apple using optionals. In the code snippet below we defined three key people in Apple history, Steve Jobs, Steve Wozniak, and Tim Cook. Then we extended Person class with two implementations of ‘isCEO’ which check if a person is CEO of his/her company.

None of them are CEOs yet at this point of their lives.

V1 is much easier to understand because it doesn’t contain any ‘!=’ operator, and we know we can use the values safely in the positive block. In comparison, not only does V2 implementation use ‘!= nil’ twice, it takes some careful checking to be sure that all forced unwrapped variables indeed wouldn’t be ‘nil’ when they are called.

Consider the following two reasoning process:

In V1, the code reads “if I have a job, the job is at a company, the company has a CEO, and the CEO is exactly myself, print a statement and return ‘true’, else return ‘false’.

In V2, the code reads “if my job is not empty, the job’s company is not empty, and the company’s CEO, which it may or may not have one, is exactly myself if there is, print a statement and return ‘true’, else return ‘false’.

Chapter 2

Jobs and Woz cofounded Apple Computers, went IPO, but both of them left Apple for different reasons. Ultimately Jobs came back, saved the company and recruited Tim Cook to join Apple.

Now we simply want to check who joined earlier. Again we have two implementations. In V1, with optional binding we defined interim variables which helped us write code which we can understand naturally like reading a sentence.

Chapter 3

Unfortunately, Jobs had health issues and eventually passed away. While Steve was on leave Tim served as the chief of Apple. So how do we know who is in charge at a moment? The following two implementations both check if current CEO is absent, if so, return the deputy chief. In our case, it was Tim.

Optional also makes it easier to provide a default value when a non-nil value is needed. For example, a company cannot operate normally without a chief person in charge, so the return value of ‘chiefV1’ and ‘chiefV2’ can’t be optional.

Chapter 4

After Tim became CEO of Apple its market capital has grown even more and became the most valuable public company. Knowing that let’s check if the company is bigger than Google or Dell.

I’ve only implemented one version in this example. Two things to notice here:

  1. There doesn’t seem to be another way to check if an optional is ‘nil’ other than using ‘== nil’ comparison
  2. When comparing ‘marketCapital > company.marketCapital’ notice both operands are optionals. Swift made it so convenient that it just works, without having to unwrap them and compare the values ourselves. It behaves just like what you would guess. However, an optional that has value is greater than ‘nil’, which is not the behavior we want in ‘isBiggerThan’. In our example, Dell doesn’t have market capital because it’s currently a private company. But ‘Optional(624.4) > nil’ yields true which is saying Apple is bigger than Dell even though we don’t have that information, thus we check for ‘nil’ at the beginning of the function.

Please recommend the article if you found the examples useful. You can read more about optionals on Apple’s website.

--

--