Optionals in Swift Programming

Gayathri Veeraraghavan
5 min readMar 15, 2021

Optionals are one of the important data types in Swift programming. In Objective-C, which is said to be the parent language of Swift, the concept of Optionals does not exist.

Before going deep into comparisons and programmatic discussions about the Optional type, let’s get to the definition and basic details of it.

What are Optionals? Where are they used in a Swift Program?

Optionals are data types in Swift which are just like Int, String etc… They are used in places where nil value could possibly occur. According to Objective-C language, nil is used as a pointer to indicate an object that has been removed or doesn't exist anymore. But in swift, nil is used to say that a type exists, but does not have any value assigned to it at all.

A variable declared with an optional type is indicated using a “?” sign instead of writing “optional” as a word.

Defining an optional variable :

Optional variables are defined as given in the following example code:

var name : String ? //A string of optional type

When an optional variable is defined and no value is set to it initially, swift automatically sets the value as nil (default value). In the above example, the string variable, “name” is an optional defined without any initial value. So, its value is set as nil by default. This optional can later be accessed inside the program by unwrapping. (Don’t worry, we’ll come across that soon in this article)

var registerNumber : Int? = 123 //We can also set values to optional type variables

Optional types only mean that nil could be a “possible” value and the variables of optional type need not be set to nil every time.

registerNumber = nil //modifying registerNumber variable as nil

In this example, we modify the Integer value we had set to the registerNumber variable to nil. Remember that not all variables in swift can take the value of nil. Only and only optional type variables and constants can have nil values set to it. Non-optionals must only have proper values other than nil.

In case you are not sure if a variable will take up nil values in future, it is recommended that you use optional types for those variables while defining. To make the concept of Optionals more clear, I’ll use some real-time examples.

Assume that each chocolate is a data type and the red box is the Optional type

Imagine that each datatype is a different type of chocolate…assume String as a milk chocolate, Int as a wafer chocolate etc. we have a few chocolates in our hand of different type. 🍫🍬🍭

Now, imagine that one among those chocolates is a gift. It is put inside a small box of its own. 🎁(You see that red-coloured gift box in the image? it has a chocolate inside it which you cannot see from outside 😋). Only after you open the box, you will be able to take the chocolate.

This chocolate gift box is like the optional type. You can access the inside content (the chocolate) only if you unwrap or unbox it.

Unwrapping is the way in which we type cast an optional type constant/variable to a non-optional type. Optional type variables are unwrapped in any one of the following ways, depending on the place where the unwrapping is done.

  1. Forced Unwrapping
  2. Optional Binding
  3. Implicit Unwrapping
  4. Nil Coalescing Operator

1.Forced Unwrapping:

Forced Unwrapping is the method where we unwrap the optional by assuming that the value it holds is not nil. Forced unwrapping is done by adding an exclamatory sign (“!”) while assigning it to a secondary unwrapping variable.

var box: String?

let hiddenChocolate : String = box!

This method of unwrapping is also done by comparing the optional value against nil and then using it further in code if the condition satisfies.

if sampleNumber != nil {

print(“This sample number contains some integer value.”)

}

NOTE: Use this method only if you are very sure that the value of the optional will never take the value nil. Trying forced unwrapping on variables that have nil value leads to runtime error.⚠️

2. Implicit Unwrapping:

This method is a simplified form of forced unwrapping. In forced unwrapping, we define an optional and then unwrap it by assigning it to a secondary variable. Here, we do it in a single step by defining the optional using the exclamatory sign(“!”) instead of the conventional question mark (“?”) after the variable name.

let stringValue : String ! = “Valid string”

let secondVar : String = stringValue.

//this secondary constant is not necessary for the unwrapping as we did it already using ! while defining stringValue

NOTE: Just like forced unwrapping, do not use this method too if you think ‘nil’ is a possible value. It throws an error. ⚠️

(Forced and Implicit unwrapping shouldn’t be done with overconfidence my friend!….it might crash the program badly!!)💥😥😵

3. Optional Binding:

In this method, we use an if statement to check if the optional value is not equal to nil. If it is a non-nil value, then we assign it to a new constant/variable. The difference between previous method and this is that in forced unwrapping we assume the value to be nil. Here, we don’t assume, instead we check and then proceed.

if let newConstant = optionalValue {

print(“not a nil value”)

}

else {

print(“it has nil value in it”)

}

Here, we don’t compare the optional with nil, but we assign the value to a new variable only if it is non-nil.

(Do you remember what I said about assigning nil values to constants/variables? Non-optional values cannot have nil values.)‼️

So if we try assigning the given optional value to a non-optional value, and it turns out to contain a nil value, the condition becomes false and cannot get assigned to the new variable we try to create. And that’s how optional binding works!

4. Nil Coalescing Operator:

This method is very similar to optional binding. We use the ternary operator (“??”) to implement this unwrapping.

Nil-Coalescing Operator is actually a type of operator in Swift language. But the special application of this operator is that it can be used for unwrapping as well!

Here, we define an optional and assign it to another variable/constant for unwrapping purpose. In the second variable, we check for nil condition and if true, then the default value is printed to avoid the nil. Else if the optional has a value other than nil we proceed with further processes using that value.

let defaultColour = “Black”

var colour = String?

var printColour = colour ?? defaultColour

//Here, since colour is nil, the default value, “Black” is printed

If the value of colour is non-nil, the value of defaultColour isn’t evaluated.

These are the methods in which we unwrap an optional value. Use them wisely and avoid fatal errors complaining to you in the console!!

Do not forget to unwrap the optionals before using it. Your compiler might think you are dumb!

Comment down if you have any further doubt regarding Optionals!! Have a Swiffttt Learning!!😊👍🏽

--

--

Gayathri Veeraraghavan
0 Followers

Happy vibed, light-hearted woman who is crazy enough to try and learn anything in the world!