What is a Swift optional 1/28/15

By Chris Johnson

By default all Swift variables must contain a value of the specified type1, and can’t be nil.

var bestCaptain:String = "Sisko" // this works
bestCaptain = nil                // throws an error

However, Swift has to work with a lot of Objective-C code and design patterns2 where variables can and are often set to nil. That’s where optionals come in. Optionals are protective wrappers around your variables. The wrapper itself tells you whether or not the variable within is set to nil, but that’s all it says. If the variable inside isn’t nil, and you want to access it, you have to unwrap the optional.

Defining optionals

Defining an optional is easy, just add a ? to the end of your variable name.

var myOptional:String? = "I'm an optional, short and stout"
myOptional = nil // totally legal

Accessing optionals

Accessing an optional is a bit trickier, and you have a few alternatives you can use depending on the situation.

Optional binding

The safest way to access your optional value is with optional binding. In optional binding, you assign the optional value to a constant if the optional value is not nil.

if let unwrappedOptional = myOptional {
} else {
    print("optional was nil")

Forced unwrapping!

If you’re absolutely sure the value should be there, you can force unwrap the optional by appending a ! to the variable.

var myOptionalLowerCase = myOptional!.lowercaseString

If the value is actually nil, your program will crash.

Optional chaining?

You can use optional chaining to access properties and methods of the underlying variable by using a ?. If the variable is nil, those properties and methods are never accessed, and the statement returns nil.

myOptional = nil
print("\(myOptional?.lowercaseString)") // prints nil

More resources

Swift optionals can be a bit confusing3, and a lot of other people have tried to explain them:

Big thanks to Scott Williams for his valuable feedback on this post. Check out his blog.

  1. Non-optional variables can be declared without a value, but can’t be set to nil. Non-optional instance variables need to have a value set in the object’s init method.

  2. Objects from the Cocoa libraries often use Implicitly Unwrapped Optionals.

  3. I wrote this post to cement my own understanding of optionals.