All About Swift Optional

Fadi Ossama
SwiftCairo
Published in
6 min readOct 25, 2019

The word “Optional” by definition means available to be chosen, but not obligatory.

What does this mean in programming?

In programming languages and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions which may or may not return a meaningful value when they are applied.

So the question that comes to mind is What is Swift Optional? Is it a concept, behavior or something else? The answer is that it’s a data type!

Let’s read this line of code

When reading this line, someone would say that its type is a String, another would say it’s a String but Optional but that’s not correct.

This line says that testOptional variable is an Optional type with associated value String.

It seems a little bit weird, no? let’s simplify it more by diving into the Optional definition.

Swift Optional definition

Swift Optional is an enum with 2 possible values: none(nil) or some with associated Value.

Let’s Now rewrite the testOptional variable in term of Optional enum:

This means that this var is Optional and in the case of “some” the associated value will be a String type.

Swift wanted to simplify things, so it made 2 forms to define Optionals: short form and long form:

They both have the same function, but the difference is that the short form is easier. That’s why it’s commonly used.

Also if we want to set value we can make it both ways using short or long forms:

Optional offers a great opportunity to give a variable the possibility to have 1 of 2 values instead of only 1 value

The difference between these 2 lines is that testString is a String var and cannot have any other value but testOptional is an Optional with Associated value String so it can be either a String or nil.

Now that we understand what is Optional, we need to know how to use it.

Imagine you have a closed Gift box,

there are 2 possibilities, the first that there is a gift inside

The other is that the box is empty

When thinking about Optional we need to think about it with the same logic, it’s a box that might have something in.

Optional binding

Optional binding is a way of using optionals, it is like you tell a friend if the box has something inside take it and use it.

If the conversion is successful, the testOptionalBinding constant becomes available for use within the first branch of the “if statement”. It has already been initialized with the value contained within the optional, which means that its type is now a String, and so there’s no need to use the “!” suffix to access its value.

In other words, if the optional binding succeeds, this means that it has value (case .some(T) if you remember from above) and then it takes automatically its associated value type which is in this example a String.

You can use both constants and variables with optional binding. If you wanted to manipulate the value of “testOptionalBinding” within the first branch of the if statement, you could write “if var testOptionalBinding” instead, and the value contained within the optional would be made available as a variable rather than a constant.

Force unwrap Optional

“Force unwrap” is another way of using optionals. “Force unwrap” is like you tell your friend: “I am sure the box has something inside. Unwrap it and use it, and if I wrong punish me! I am 100% sure there is something inside.”

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.”

But you’ll be punished if it has nothing inside, because trying to use “!”to access a nonexistent optional value triggers a runtime error which means that your app will CRASH.

Implicit unwrap Optional

Now that we know both “optional binding” and “force unwrap”, we can now know that there are 2 ways to declare a variable as optional.

The first one “testOptional”, when declared this way, it means that each time you try to use it please make sure it can be nil, so use any of the above-mentioned ways to use it’s associated value.

The other one “testImplicityUnwrapOptional”, when declared this way, it means that it’s already unwrapped, so you can use it with its associated value whenever needed and no need for both ways as we’ve already used the second option implicitly. But also take care that as we are unwrapping it without checking its value, then if it’s nil you’ll be punished.

Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined, and can definitely be assumed to exist at every point thereafter.

You can think of an implicitly unwrapped optional as giving permission for the optional to be unwrapped automatically whenever it’s used. Rather than placing an exclamation mark after the optional’s name each time you use it, you place an exclamation mark after the optional’s type when you declare it.

Optional chaining

“Optional chaining” is like having multiple boxes inside your box, so you apply all the above rules but in a chain of possibilities.

In the above example, we are using the optional binding but on 2 levels. We are not directly binding the optional “house” but rather we are telling the compiler: if you can bind continue, otherwise break and continue code execution.

Another example of optional chaining is when working with methods like the below example:

Here we are also telling the compiler: if you can bind “testOptionalBinding” continue and call method1, otherwise break and continue code execution normally without throwing a runtime error.

To define “Optional chaining” in a clear definition we can refer to Apple’s Swift Documentation:

“Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.”

Nil coalescing

The last way to use Optional is “Nil coalescing”.This option is about giving a default value to a variable, if the optional variable you are trying to bind is nil.

That’s all about Swift Optionals, it’s easy and very useful, thanks to Apple that made all these valid options.

--

--