The Basics of Optionals in Swift

Optionals allow variables to not have a value. This is similar to having a variable set to nil in Objective-C. The biggest difference is the amount of safety Swift has baked into the creation and management of optional variables.

I’m finally getting confident using optionals, so I wanted to share the basics and show some code samples of how to use them.

The first aspect to understand is how Swift deals with the creation of instances and properties. There are only three ways a property can be correctly setup:

  1. Given a default value inline with its declaration:

    var firstName = "Russell"

  2. Given a value in the designated initializer:

    init(lastName : String) { self.lastName = lastName }

  3. Marked as an optional, allowing the property to not have a value at

    instantiation time: var image : UIImage?

Here is how a Person class would look using all three rules:

class Person {
  var firstName = "Russell"
  var lastName : String
  var image : UIImage?

   init(lastName : String) {
   self.lastName = lastName

We want a person’s image property to be absent until the user chooses a photo for them.

Now when we segue to each Person’s detail view controller, we can check to see if selectedPerson.image has a value. If it does, great! We can set our imageView.image with it. If not, we will keep our placeholder image:

if self.selectedPerson.image {
  self.imageView.image = self.selectedPerson.image!
else {
  self.imageView.image = self.placeHolderImage

You are probably wondering what the ! was for at the end of the 2nd line. That’s called a forced unwrapping in Swift. You are telling Xcode that you know for a fact that this optional property has a value, so now you want to access it. Forced unwrapping allows you to use the values inside optional variables.

If we take the question mark off the property declaration, Xcode quickly slaps us with two errors. First, it tells us that Person can no longer properly init, because the image property isn’t properly initialized:

Compiler Message 1

It can’t be empty without that question mark. Second, it tells us the if-conditional we setup, where we check if selected.Person isn’t empty is no longer valid:

Compiler Message 2

Since the image property isn’t an optional, Xcode is telling us that there’s no need to ever check if it’s empty or not, because it can never be empty since it isn’t an optional! This ties in with Swift’s focus on safety. Thanks, Dr. Dre!

You can find the project that the above code snippets were excerpted from on Github.

Get job-ready in Swift »

Next PostPrevious Post

About the Author