What are Optionals in Swift?

Optionals are a feature of the Swift language that is not normally seen in any other language. So why did Apple go through the trouble of adding optionals to swift? Well it turns out that they make our lives a little easier (however maybe not at first).

A very common error that occurs in programming is a Null Pointer Exception. Normally when you create an object you create a variable that points to that created object in memory. A Null pointer occurs at runtime when you have a created a variable that is points to NULL and are trying to access an object that is not there. 

Take for instance:

let myVariable = UILabel()

myVariable.text = “Label Text”

Here I am creating a variable called “myVariable” and setting it to point to a UILabel object. This is what that looks like visually.

VariablePointer.png

So when you are calling “myVariable.text”, “myVariable” is only a pointer to the actual object so the method is being called on the object that the variable is pointing to.

However, in a lot of languages, it may be the case that this happens.

VariablePointerNull.png

In this case the variable exists but the object does not. So this would cause a Null Pointer Exception if you were to try and call any methods on a non existent object. 

Optional Syntax

Swift aims to take care of this common situation by introducing optionals.

By default, every variable in Swift “must” have a value. So it is not possible (without optionals) to have a variable point to NULL like the image above. However, sometimes it is necessary to create variables that have no value. For example, if you have a Text Field and expect the user to enter some text, you may not know whether the user has actually entered something or not. Therefore if you called “var textEntry = textField.text”, the variable “textEntry” is not guaranteed to contain a value, it might point NULL if there is no text entered in the textField.

Thats where optionals come in!

An optional is a modifier that can be added to variables to specify that they might or might not contain a value. If they do contain a value, the variable will act naturally. If not, then the variable will point to “nil” (NULL in swift).

How is this different?

There are some cool tricks that you can do with optionals. For example, optional binding will allow us to more elegantly deal with optionals. 

Take a look at the following code.

if let textFieldText = textField.text{

            print(textFieldText)

}

Here you see the keywords “if let”. What this is saying is “if  textField.text contains a value, put it in the constant textFieldText and run the block of code, if not then skip the block of code and continue on.” This way you can check to see if a variable has a value and if so run some code. Note that in textField.text, the text property is a String? (String optional).

Another optional trick is called optional chaining. This is used when you are not sure whether there is a value or nil pointed to by a variable.

Take a look at an example of optional chaining that involves optional binding.

 

let user = User()

if let friendsInfo = user.friend?.information {

        print(friendsInfo)

}

What this code does is create a new object of type User, which has two properties, friend and information, friend is a reference to another User type and information is just a String optional. The next line says “if user.friend exists, retrieve the information and store it into the friendsInfo variable”. Then the code within the block of the if statement prints that information.

Optionals save time. By just adding the “?” character we are handling the possibility of a “null pointer”. In this case, if the “user.friend” points to nil, then the following block of code will be skipped!