Mobile Opinion Tech Talk

#Techtalk: Swift Recipes: Optionals Not knowing Optionals is not an option!

Why was a Swift developer arrested on the beach?
Because he thought clothing was optional.

Traditionally, we have all dealt with variables as having some value at any point in time during the execution of the program and use them assuming they will contain some value.

Having a value of nil is also considered as a legitimate value since we use it for comparison operations just like it’s another value. In essence, we are used to variables that have a single state of existence, a value-full state. Swift changes that with Optionals and its close cousin Implicitly unwrapped optionals by introducing a new state, a value-less state.

Before getting into the details of the optionals, let’s have some fun with a little story. Imagine you get a Christmas gift from an unknown sender. You are very excited to have received a gift and eager to open it and see what it is. But at the same time you are a bit apprehensive since you are not sure what it contains. Could it be an Xbox One that you have been longing for, or could it be some kind of a cruel joke someone’s playing on you. You are left pondering with a big ? over your head.

swift2

The Optional variables (or constants) are similar to this gift box. It could either contain a value or no value at all. You create an optional variable by placing a ? after the type of the variable.

[code lang=”js”] var contentsOfGiftBox:String?
[/code]

Once you define a variable as a optional it means that it can either contain a legitimate value of the corresponding type or it could be in a value-less state represented by nil.

Now going back to our story, wouldn’t it be nice to have X-ray vision of Superman to be able to peek into the box without opening it? And once you know what it contains you can decide whether to unwrap it and enjoy the gift or just throw the box away. If you didn’t have this capability and opened the gift right away, your excitement would come crashing down if the gift box was empty.

boxThat’s exactly what happens in Swift if you unwrap the optional that has no value. If you were to access the contents of the optional variable without binding it first you can use the ! operator. But the app will crash if the variable is in a value-less state.

[code lang=”js”]let gift = contentsOfGiftBox![/code]

Luckily Swift doesn’t like to play cruel jokes on us. It provides some constructs akin to the Superman’s x-ray vision. One of them is the if-let construct that lets you bind the optional variable to a normal variable without crashing the application.

[code lang=”js”] if let gift = contentsOfGiftBox
{
enjoyYourGift(gift)
//OR enjoyYourGift(contentsOfGiftBox!)
}
else
{
throwAwayTheGift()
}
[/code]

Another construct is the guard statement which can be written as:

[code lang=”js”] guard let gift = contentsOfGiftBox else {
throwAwayTheGift();
return
}
enjoyYourGift(gift)
[/code]

The system dynamically determines at run time if the optional contains a value and if so binds or assigns its value to a local variable. If not it simply goes to the else part or in case of guard the point after the else block.

So what we have learnt so far:

1. Optionals provide variables with two states. value-full state and value-less state
2. Create an option variable as var|let identifier:type?. Default is nil or value-less state
3. Assigning to an optional variable as identifier = value | nil
4. Unsafe unwrapping the optional value as identifier!
5. Safe unwrapping using if let value = identifier { //use value safely }

Implicitly Unwrapped Optionals

In our story earlier, imagine if you have wrapped the gift yourself , you would unwrap it knowing for sure that its not going to be empty. Or perhaps its a gift from your parents who wouldn’t play some kind of a cruel joke on you for your birthday. So you are 100% sure that the gift box will not be empty when you open it.

Swift provides a different kind of optional for this situation. They are called implicitly unwrapped optionals. They are very similar to optionals except that once they are set with a value its guaranteed that it will contain a value forever (unless you change it to nil)

[code lang=”js”]var giftBoxFromMother:String![/code]

When you read this variable you don’t have to ponder (?) whether it’s going to be empty or not. You can just access it just like any other normal variable. The system has implicitly unwrapped it for you. However, this assumption is solely made based on your application logic. It is still possible to set an implicit unwrapped variable to a value-less state by setting it to nil and any attempt to access it without binding will crash the application.

Back in our story imagine if the gift box from your parents was delivered to you thru your brother who’s jealous of you and removes a gift and sends you an empty box. It’s your responsibility that you get the gift directly from your parents so that you can open it without questioning its contents. If you ever feel like it has passed through multiple hands make sure that you use your X-ray vision to inspect the contents before opening it. In other words  use the if-let or guard constructs when programming in Swift.

Hops this small article has helped you in understanding optionals.

Note: Please wear clothes when going to the beach. Clothing is not optional yet!

Pradeep Kumar
VP - Technology Innovations. He is a geek by nature, loves to code and write tech articles.

Leave Your Comment

Your Comment*

Your Name*
Your Webpage