Swift Optionals

In this tutorial you will learn about the Swift Optionals and its application with practical example.

Swift Optionals

In Swift, when we declare a variable they are non-optional by default, which means you are required to assign a non-nil value as initial value to that variable. If you not assign an initial value or try to set a nil value to it, you will get a compile time error.

Lets take a look into following example code –

Here we have defined some variables, It’s all good with the above declarations until we try setting it as below.

In the above code we have not assigned any value to “fname” and we have assigned “nil” to “lname”, now when we run the above code, it will throw compile time error because in swift variables are non-optional by default. So if a variable is defined without assigning any initial value or nil value it will generate a compile time error.

In order to overcome this problem swift introduced a data type called “optional”. Optionals is a powerful feature which allows variables and constants to hold non-existing or nil values.It gives you way to anticipate a ‘nil’ value and still keep your app running safely, Optionals can also be used to anticipate values that are nil at the moment, but later on might not be.

In Swift, Optional type variables or constants can hold value or nil value.

Declaring Swift Optional

Optional can be defined by using question mark (“?”) operator after the type declaration.

Syntax:-

Example:-

Here, we have declared two Optionals with different data types, when we execute above program it does not throw any compilation errors instead we will get the output as following –

Output:-

Optional types is like a wrapper over the normal data types which allow the variable/constant to hold nil value, thus when we print an optional variable/constant it wrap the value inside Optional().

Swift Optional Unwrapping

In the above example we have seen, when we print an optional variable/constant it’s values is wrapped inside Optional() as following –

thus in order to access the value out of it, we need to unwrap it. Swift Optional unwrapping gives you way to convert an optional type to a normal type.

Optional unwrapping can be of following two types –

  1. Force Unwrapping
  2. Implicit Unwrapping

Swift Force Unwrapping

An Optional variable/constant can be unwrapped by appending exclamation mark (!) at the end of the variable/constant name.

Example:-

Output:-

Swift Implicitly Unwrapping

In the above example we have unwrapped an optional variable value manually using exclamation mark (!), but implicit Unwrapping allows you to unwrap optional value automatically.

When we want to unwrap an optional variable/constant value automatically then we have to declare optional with exclamation mark (“!”) instead of question mark (“?”).

Example:-

Output:-

Swift Optional Binding (if let)

There is a much safer way to unwrap an optional, lets have a look at below snippet –

The above statement allows us to first check if the “site” is not nil before we force unwrap and print its value, as “site” doesn’t have a value, which means it will not be forced unwrapped by accident.

In Swift, there’s a more elegant way to acheive the same is called optional binding. Optional binding is the recommended way to unwrap an optional. Let’s have look at below code snippet –

Example:-

Output:-

Here, in the above example we assign the value stored in the optional variable “site” to a temporary constant “siteName”, which is then used in the if statement. Here the value of the optional variable “site” is bound to the constant “siteName” and used in the if statement.

Swift Optional Binding (guard let)

Guard let is similar to if let, but unlike if let the guard statements only executed in the case when optional value is nil.

A guard let is preceded by an “else” block which is executed when optional value is nil. Guard statement works only inside a functions. Lets have a look at following code snippet –

Example:-

Output:-

Here, guard expression checks whether optional constant “age” contains a value or not. If “age” contains a value then guard-let statement will unwraps the value and places the unwrapped value in temp constant. Otherwise, else block gets executed when “age” is empty or set to nil and it would return to the calling function.

Nil-coalescing operator

There may be chance we want to use a default value when an optional is nil. In Swift, there is a Nil coalescing (??) operator allows you unwrapping an optional if it has a value, or providing a default value present on the right hand side if the optional value is nil.

Example:-

Output:-

 

 

In this tutorial we have learn about the Swift Optionals and its application with practical example. I hope you will like this tutorial.