Anybody learning Swift or how to program for that matter would take some time to chew on the concept of Optionals. The most conventional language where the idea of Optionals made its appearance is in Haskell. It does not, however, exist in C or Objective-C.
It all boils down to the fact that a value may not exist. Suppose you’re a bank, and you need to keep track of customers who open a bank account with your branch, and that it’s branch policy anyone opening an account will need to have a checking account. The other product that your bank offers is a credit card account which is… optional. Writing a simple class in Swift, it may look something like this:
Here, what’s optional in the class BankAccount is the Credit Card Account. Its “optionality” is denoted with the question mark as a variable and the signature for instantiation. So, a bank account may have a credit card account tied to it, but it may also be nil. I can instantiate it in either of the following manner:
Either would give me a valid BankAccount object that I can work with.
Suppose you want to extract both the checking account and credit card account information so that you can display it to the customer when they log in to their account on a website.
Line 4 is business as usual, as you’re able to print the checking account number of the bothProducts object by accessing the checking account property. Line 7 is the optional in action — though it’s printing out some numbers, it’s wrapped around by the Optional. If you’re attempting to assign this value to a text label for example, it would literally read: “Optional(“109876”). This is something you wouldn’t want in practice. What you would do is “unwrap” the optional such that you can get the actual value. On line 10, I’m forcing the unwrapping of the optional. This is seemingly awesome, but in the instance that the optional contains a nil value, it would induce a crash.
Above being a wizard in coding, a 10X engineer, or for that matter, a .1X engineer, as a someone who makes apps, you should aim to reduce all possible and foreseeable crashes. Having a program crash has consequences when it comes to retaining users – they’ll most probably delete the app from their phones immediately. The most recent bug where Safari crashes upon touching the textfield probably cost some engineers their jobs.
So, you should really only forcibly unwrap an optional with an exclamation point only if you know for a fact that it would not be nil. Often, this is if you’re working with something that’s hooked up to Interface Builder, but, there are other cases.
So how should you unwrap the optional for use in your code? You do an optional binding.
In the first case, we’re unwrapping the object of the account that only has a checking account associated with it. What’s occurring on line 1 is that you’re assigning the optional value to a constant variable “creditCardAccount”, which in turn is ready for use if in fact it exists. Because the first line does not evaluate to true, line 4 executes, and we print out: “The guy has no credit card”.
In the second case, an assignment is successful, and because the variable is not nil, line 11 executes, and we get the credit card number associated with the account.
I’ve read someone somewhere comparing Optional Binding or Optionals as those little dolls that contain other dolls. It’s a cute comparison, but I like to think of the nil value as a explosive, and Optional Binding as the robot that checks/attempts to defuse things before sending people into a confined area. Or, it’s like the little window mirror that Blackjack dealers peek through when they have an exposed 10 or A in Vegas – the Blackjack dealer departs from “standard” play and reveals her cards.
When you first jump into Swift, you may be tempted to just quell the warnings and suggestions to use the ! to unwrap optionals, but you’ll be better served in the long run to meditate on the concept before going too far.