Codementor Events

Optionals and Optional Binding from beginning.

Published Dec 12, 2018Last updated Sep 21, 2022
Optionals and Optional Binding from beginning.

Introduction

Optionals are one of the exciting and neatest features in the Swift programming language. It might seem daunting at first, but it is instead a straightforward and compelling topic once you understood it. The objective of this tutorial is to learn what are optionals,? and ! and what are some problems with using optionals and how to unwrap the optionals the wrong way and then how to use it safely.

What is it and why do I use Optionals

Optionals are nothing but something to deal with the nothingness of data. The idea behind using the optionals is to deal with a situation where data can be nil or missing.

Let's see the following example

import Foundation

var name:String = "Vinayak"
var middleName: String = ""
var lastName:String = "S."

Now in the above situation, I've the first name, last name, however, the problem is I don't have any middle name so, what should happen to deal with such a situation. As you might have guessed we need something so that we can set that property to nil or nothing because we do not have any information regarding it. In such situation we use optionals.

So let's improve the code and make use of optional.

import Foundation

var name:String = "Vinayak"
var middleName: String?
var lastName:String = "S."

So now we have introduced this "?" at the end of the declaration so does that mean you might be thinking 🤔. So, the answer is it is an optional value which means value for this may or may not be available.

Now let's observe something Interesting

import Foundation

var name:String = "Vinayak"
var middleName: String?
var lastName:String = "S."

name = "Harsh"
middleName = "Kumar"
lastName = "P."

print("The first name is", name)
print("Middle Name is ", middleName)
print("The last name is ", lastName)

Now In the example above I've changed the name, middle name and last name to other values as it is a variable and mutable, if your are not sure about it I would recommend you to read my other post on variables and constants in swift click here. Now when I try to print this, we get a warning.

Screenshot 2018-12-11 at 11.09.06 PM.png

🤷‍♀️Now What is this Warning You might be thinking?

The reason for this is a warning is because we are trying to print something which may or may not have any value in that. If we are printing the optional which does not have any value the program will crash. So, before moving on the solutions to this problem let's look at what fixes Xcode gives me.

Second Warning Fix given is ! (Force Unwrapping)

forceUnwrapping.png

This solution fixes the warning and now! Means that I am sure that there is always value for this optional variables and if it is nil then the application will be crashed. Not Recommended! unless you are 100% sure that the optional variable has a value and cannot be nil. Now if we want to use the optional value we need to extract it, and that's called Unwrapping and In this case, we force it to give me value. That is the reason we call it Force Unwrapping

How can we Unwrap optionals safely.

**if let statements **

import Foundation

var name:String = "Vinayak"
var middleName: String?
var lastName:String = "S."

name = "Harsh"
middleName = "Kumar"
lastName = "P."

print("The first name is", name)


if let middleN = middleName{
    print("The middle Name is ", middleN)
}else{
    print("There is no Middle Name")
}

print("The last name is ", lastName)


so the above statement is what we call optional binding or safe unwrapping. The if let condition above check if there is value in the middleName then assign in variable MiddleN and print middleN. But if there is no value it goes to else block and prints there is no middle name

Discover and read more posts from Vinayak Sareen
get started