Learning Swift : Optionals

 

Hello Friends,

Megha here, 

Have you guys read “Dark Places” by Gillian Flynn? I recently finished it. It is a pretty awesome murder mystery. It is a story of a girl who loses her family at a very young age in a horrible episode. When she grows up, she ventures on a journey to find out what exactly transpired that day. Do give it a read. You can find its review here.

Enough about the book. In this post, we will be learning about ‘Optionals Data Type’.

This data type is exclusive to swift. You wouldn’t find it in any other programming language such as java or python.

In our previous post, we deliberated on Type Safety property of Swift. Go ahead and visit it.

Not just with types, Swift is otherwise also a very safe language.

In case of java, null values can be assigned to variables and constants. That is not allowed in Swift.

Why not assign a nil value to a swift variable and see for ourselves?

 

//variable to store your favourite color
var favColor : String = nil

 

optional error 1

 

 

The compiler immediately throws an error “Nil cannot initialize specified type “String” as we expected.

Another example:

 

//constant to store your age
let age : Int = nil

 

screen-shot-2016-11-07-at-8-39-31-pm

 

Similar error for this one too!

It can also be seen that compiler is suggesting a fix add “?” around type “Int” / “String” to make them optional.

Swift has given this feature so that you can have a variable or constant which if not initialized can contain a “nil” value.

What are we waiting for? Let’s remove this error from both our variable and constant by making them optional types.

 

var favColor : String? = nil
let age : Int? = nil

 

optional no error

 

 

We can clearly see, error vanishes like magic.

Now we are going to assign a value to our variable:

 

var favColor : String? = "Red"

 

It will work without any more impediments.

Hmm.. But we must check if we can assign an integer value to this string optional. Shouldn’t we?

 

var favColor : String? = 78

 

optional error 3

 

Uh-oh! Compiler has thrown and error “Cannot convert value of type ‘Int’ to specified type ‘String”

It means we can only assign ‘nil’ or string value to this optional variable.

So far we discussed two major items :

  1. Optionals are declared using a “?”
  2. They can store either “nil” value or a value of that particular type

 

Okay, Let’s try and use this optional variable. 

 

print(favColor)

 

print optionals

 

It is being printed. But we can see, it has got itself wrapped inside Optional() keyword.

We wouldn’t want that while using it somewhere else. Right?      

So how do we unwrap an optional value?

We do it by placing “!” after the variable while using it like this:

 

 

print(favColor!)

 

optional print 2

 

We can see now only “Red” is printed.

 

Optional Binding

 

It can be used to find out whether an optional variable contains a value or nil.

 

var favColor : String? = "Red"
if let color = favColor{
    print(color)
}else{
    print("No color")
}

 

Here we declare an optional favColor and assign a value to it. Then use if let….else to test whether optional has value.

If let first checks whether the optional has a value. If it has no value, else statement is executed. If it has value then that value is implicitly unwrapped and assigned to the constant color, and following statements are executed. This is called Optional Binding.

 

optional binding 1

 

optional binding 2

 

We will learn more on the if-else and other control flow statements in our next post. Till then practice optionals and leave your questions and thoughts in comments.

 

PS : You can find the source code of this post here.