Optionals in Swift
Tags: ios, swift
Published: 2018-01-15 18:45:44

---
title: Optionals in Swift
published: true
description: Optionals in swift
tags: ios, swift
---
![](https://cdn-images-1.medium.com/max/2000/1*K_ASFaz5nY8Ft1f2ZtV3bA.jpeg)

### Absent of&nbsp;Data

There are situations where we wish to accept data from users and also provide an opportunity for some of the data to be optionals, meaning they are not required but should be provided if available.

{% gist
  https://gist.github.com/agoiabel/762af989d8070e409780deaea606964e 
%}

The constant `me` instance of a person provided all the data but the constant `anotherPerson` cannot provide all the data because he probably does not have a middlename. Hence he passed `nil` as the value of the `middlename`. Sounds cool right but the `nil` passed will cause an error, Why?, because we have not told swift to make the middlename `optional`.

### What is an Optional in&nbsp;Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a&nbsp;`?`to any type:

```
var middlename: String?
```

The above means that middlename can either be a string or does not contain anything which is represented by the&nbsp;`?`. _An optional is a kind of container. An optional String is a container which might contain a string. An optional Int is a container which might contain an Int_. Think of an optional as a kind of parcel. Before you open it (or “unwrap” in the language of optionals) you won’t know if it contains something or nothing. Its only an `Optional` value that can be set to `nil`, and that was the reason for the error when we passed the `middlename` a value of `nil` without specifying its a type of `Optional`.

```
var red: String = "Red"
red = nil // error: nil cannot be assigned to type 'String'
```

### How to create an Optional?

The simplest way to create an `optional` in swift is to add&nbsp;`?` in front of the type like below

```
var middlename: String?
```

Another way is using the Optional keyword like below

```
var middlename: Optional<String>
```

### Using (unwraping) an&nbsp;optional

The simplest way to unwrap an optional is to add a&nbsp;`!`after the optional name.

{% gist
   https://gist.github.com/agoiabel/617db4b943a984e6f2dea0d2ce2fdfed 
%}

Notice the `\(middlename!)`, the&nbsp;`!` there is use to unwrap the middlename so we can get the value “abel”. The problem is that when we passed a `nil` value to the middlename, we will get a runtime crash which says `nil is Unexpected`.

{% gist
   https://gist.github.com/agoiabel/6d077f65eb18a3b523d1812d19b5e566 
%}

Before unwrapping, we need to be sure that there’s a value. So therefore we are going to continue the rest of the article with how to check before using (unwrapping) optionals.

#### Use If to Check for nil before force unwrapping:

Since it was `nil` that was passed to the variable when we initialized the Person struct, we can use an if statement to check for `nil` before unwrapping the `Person` struct like below

{% gist 
    https://gist.github.com/agoiabel/330cff2bc1285a95ce8de860a120ce44 
%}

Whenever we use the&nbsp;`!` symbol, it is denoted as force unwrapping the optional value, but it a common practice to avoid force unwrapping it, because we can write our code in such a way that swift will automatically unwrap it for us

#### Using Optional&nbsp;binding:

With optional binding, though we are still using if, swift provide a way for us to use the `if let` statement then automatically unwrap it for us like below

{% gist 
   https://gist.github.com/agoiabel/7c996179776779c1b431c154d845c4a4 
%}

#### Using Guard for early&nbsp;exit:

Guard provide a way to quickly exit when checking for the `optional` string and make our code much more cleaner hence there wont be need for `if else` statement.

{% gist 
   https://gist.github.com/agoiabel/615e44ec0695d4d20499925dda9dd55d 
%}

We have covered how to use optionals in swift, let us look at some cool secondary use cases of optionals which include using `multiply optionals`, `method chaining` and `Nil Coalescing`.

{% gist 
   https://gist.github.com/agoiabel/7676f7f6b3023f304804077ecab895dc 
%}

The `streetName` in the Street class is an optional string, the `House` class has a street variable which is also a Optional Street. The Person class too has a variable house which is an Optional house. When we have to access the person street. To access the person street (myStreet), we ain’t sure if the person gave us the house information (myHouse). That was the reason why we use the `if let myHouse = Person.house`. If the `Person.house`is empty, the if statement will fail to execute, else the variable will be assigned to the `myHouse` property. Next, we have to access the `myHouse.street` and if its available, the variable will be assigned to the `myStreet`.

{% gist 
   https://gist.github.com/agoiabel/e88128f60c294d762e7611fafc5e444e 
%}

The pattern used to access the myStreet can be improved with the use of optional chaining like below:

{% gist 
   https://gist.github.com/agoiabel/a731cbda92c67fbd1cff7aecbdd39309 
%}

I am happy to share this article with you. If you’ve enjoyed this article, do show support by loving it . Thanks for your time and make sure to follow me or drop your comment below 👇