Optionals in Swift

Ashish P
iOSMastery.com
Published in
2 min readJul 8, 2018

--

Swift introduced a lot of great features one of them is optional. An optional is used where a value may exist or not. This concept doesn’t exist in C or Objective-C. In objective-c if a function returns the absence of an object it would return nil. So we need to handle this case, with something like

Object Validation in Objective-C

But this doesn’t work with structures or enumerations where in case of absence of value we will get NSNotFound.

In swift we have a single type optional which can handle any data-type if it is absent or present.

An Optional can be declared by putting a ? mark after data-type of a variable.

Optional declaration

where name is an ‘optional’ where a value of name could be nil. Infact if we don’t initialize the name variable with a value, it is automatically set to nil.

Optional default value is nil

Here lastName is set to nil.

Force Unwrapping

Syntax:-

Putting ! after the optional value unwraps the optional. i.e. returns us the value inside the optional. This is called as force unwrapping. It is like telling the compiler that I know theres a value in the variable, give me the value. Force unwrapping a variable which contains a nil value will produce a runtime error.

To handle the nil case, create a temporary constant or variable and assign it the optional. Then check if the const contains the value i.e. not nil.

To check if Optional contains non nil value

Optional Binding

The above declaration and ‘if’ condition can be combined as follows :-

Optional Unwrapping in Swift

This way we can check if the optional contains the value or is nil. If it contains the value, only then the block of code inside the ‘if’ condition is executed. This is called as optional binding. This makes the code safer and easier to debug.

Implicitly Unwrapped Optional

Sometimes the value of an optional never changes once we initialize it. Thus it is safer to assume that optional exists. We can safely avoid checking if the optional contains a value.

Unlike forced unwrapping where we force the optional to give us the value, with implicitly unwrapped optional we specify that the value exists at the time of its declaration. Thus we don’t have to unwrap it every time we use it.

Consider the following example:-

smart alternative for force unwrapping

Each time we want to use an optional value , we have to unwrap it with an ‘!’

Implicit optional removes the need to do so. We can access an implicit optional value just like a normal variable or constant.

implicitly unwrapped optional

Thus we can assign an implicit optional like a normal String. No need to unwrap every-time you want to use it.

Note: Just like a Forced Optional, this can produce a runtime error if optional value is nil. Thus use it only in case where you are sure that optional contains a value.

--

--