Optionals: to Be, or Not to Be, That Is the Question

Dani Devesa
Falzia - Swift

--

For a Swift newbie, optionals can be the first bump in the road you may find. Not just because of the concept (it is a type that handles either a value or the absence of it), but because of a very particular syntax. Yes, we finally got rid of all our Objective-C like square brackets and most of the ‘@’ symbols of our weird code, but be prepared to see some funny ‘?’ and ‘!’ characters.

Declaring an optional is easy. Imagine you need a struct for storing names. Everyone has a forename and one or more surnames, but the middle name could be something optional. Here it is how our code would look like:

Simply by adding a ‘?’ after the type, we are telling the compiler that middlename can either store a String or be empty (nil).

We could initialise our Name structure like this:

But note that if we try to pass nil for the forename or surnames parameters, the compiler will complain saying that nil is not compatible with the expected type. And here it is where the magic of optionals starts. We don’t need to check if the user has passed the necessary values inside the methods, because the signature implicitly says which parameters are optional and which are not. Also note how cool it is that when declaring a struct in Swift, we get an init method for free, we don’t need to declare it.

But let’s start from the beginning…

The Basics

We’ve seen how you can declare an optional: just with the type it may contain and the ‘?’ character.

Now we can assign it either an Int value or nil. Both will work.

Now try to assign nil to an Int variable… You’re right. The compiler will tell you that “Nil cannot be assigned to type Int”.

Unwrap It!

Try to print the previous value.

Strange, isn’t it? To get the value inside the optional you have to unwrap it first with the ‘!’ mark.

But unwrapping optionals is dangerous. If you try to unwrap an optional that is nil, bad things will happen. That’s why you should always check first if the optional has a value.

Optional Binding

That’s such a common pattern in Swift that there is a special structure for doing it and it’s called optional binding. Imagine a user enters a number in a text field and you need to convert it to an Int. It could be done as follows:

Last, but Not Least Important: Implicitly Unwrapped Optionals

Specially at the beginning, it can be quite confusing to see an optional declared with ‘!’ instead of ‘?’. It is used when it has not been initialised at the beginning but you are confident enough that it will have a value when you use it.

Note you don’t have to unwrap it to get the value. Because it is implicitly unwrapped, it will do that for you. Be careful though, if you use it and it doesn’t have a value yet, you will get a fatal error.

That’s why you can still use optional binding with implicitly unwrapped optionals to check if it contains a value.

The most clear example of this is when declaring an IBOutlet. It is not initialised at the beginning, but the Storyboards will do the binding for you so you know that it will have a value when you use it.

And that’s it! It is not that difficult, is it? Swift will help you to write type safe code, that’s one of the main goals of the language. And while a little bit confusing at the beginning, you will see the benefits of optionals as soon as you start using them.

Stay tuned for more about optionals, Swift or iOS Development in general on upcoming posts!

Resources:

The Swift Programming Language (Swift 2.1) -> The Basics -> Optionals: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

Udacity -> Learn Swift Programming Syntax -> Lesson 2: Optionals: https://www.udacity.com/course/learn-swift-programming-syntax--ud902

Swift Translation Guide for Objective-C Developers -> Chapter 5: Optionals: http://www.amazon.co.uk/gp/product/B00QFI5S8U?ie=UTF8&camp=1634&creativeASIN=B00QFI5S8U&linkCode=xm2&tag=falswi-21

--

--

Dani Devesa
Falzia - Swift

Software Engineer — #iOS @Spotify. I wrote a book: “Developing Accessible iOS Apps”. Opinions are my own.