UNDERSTANDING OPTIONAL DATATYPE AND ITS UNWRAPPING IN SWIFT

Aviral Yadav
3 min readApr 21, 2020

Optional is a rather interesting datatype in Swift. It basically means that whether the variable(which is declared optional) either stores/holds a value or does not store/holds a value(nil in this case).

Note that 0 and nil are different things, the difference being 0 is a numeric value and nil simply means nothing or null value.

Syntax for declaring string optional

In the above image, I have declared a string optional . This implies that are optionalex1 variable may or may not be storing a string.It can be initialised to nil according to the wish of the user. You can press and hold the option button on your keyboard and click the ? to know the datatype of our variable optionalex1.

Note: Although I have used a string optional here, it is possible to create integer, floating optionals too.

optionalex1 has the datatype string optional

UNWRAPPING AN OPTIONAL

The optional is unwrapped when the user is absolutely sure of the fact that the variable contains a value certainly. The force unwrapping is done with the help of ! symbol .

Unwrapping optionalex1

In the above example , we are sure of the fact that our variable stores a string value and we can unwrap it.

Consider the following example:

What do you think is the datatype of optionalex2 ?

Well ,I guess you are right. It’s a String datatype, since we have unwrapped our optionalex1 which then becomes string and stored it in optionalex2.

However, let’s see at a counterexample:

What if we initialise optionalex1 as nil and then try to unwrap it?

Well , the compiler in this case shows an error, reason being the fact that optionalex1 is nil i.e. no value is stored in it and we are basicallly unwrapping an empty value. We are basically trying to print nothing which does not make any sense.

In iOS development . we come across many scenarios, where our variable may be optional and we try to unwrap it. To prevent this condition , we use techniques such as optional binding and optional chaining.

Though I will talk about optional binding and chaining in my upcomig articles, here is a short example of using if-else to prevent the error condition:

Condition when optionalex1 is a String, outputs “Aviral”
Conditon when optionalex1 is nil, no value is printed

I hope I was able to clear your doubts with this article.This is my first article on medium and I hope you liked it. Thanks for your time and do follow me for some interesting articles related to iOS development .Thank You :) .

--

--