Workshop 16: Optional

An optional is a Swift type for declaring a variable that can hold either a value or no value. In this workshop you will learn:

Before you begin, I assume you’ve done the following:


Declaring a Variable as An Optional Type

When you declare a Swift variable in a playground file or a Swift class file, you must assign it an initial value before using it. Failure to do so will result in the compiler complaining. What if you want to use an empty variable in a playground or Swift class file. Well you can, by declaring it as an optional type. Here are two ways to declare an optional variable.

var foodName: String?
var foodPrice: Float? = 2.99

{Some 2.99000000953674}

On line 01, an optional variable called foodName was declared by appending its type with a question mark (?). The compiler initialized the variable with the value nil. This mean it has no value, it is empty. On line 02, an optional variable called foodPrice was declared by appending its type with a question mark (?). It was initialized with the value 2.99.

Some places optionals are useful:

  • When a property can be there or not there, like outputTextView in a ViewController class
  • When a method can return a value or nothing, like searching for a match in an array
  • When a method can return either a result or get an error and return nothing
  • Delegate properties (which don’t always have to be set)
  • For weak properties in classes. The thing they point to can be set to nil

Forced Unwrap an Optional Variable

Now, to access the value inside an optional variable, you have to forced unwrap it by using the exclamation (!) mark like this:

if (foodPrice != nil) {
    println("The foodPrice variable has this value \(foodPrice!)")
// Output
"The foodPrice variable has this value 2.99

Above code is telling the compiler to check the foodPrice variable to see if it have a value other than nil; if so, forced unwrap the variable and print its value. Force unwrapping an optional variable, allows you to use its value.

Optional Binding an Optional Variable

Instead of using an exclamation mark (!) to forced unwrap an optional variable; you can use optional binding to unwrap an optional variable. Optional binding check the optional variable to see if it have a value or not. If it does, unwrap the optional variable and put its value in a temporary variable or constant. Here is an example of how to use optional binding to unwrap an optional variable.

// Declare and initialize an optional variable
var softDrink: String? = "Pepsi"
if let drink = softDrink {
  // Display the drink constant's value
// Output

In plain English, above if statement says, “If the optional variable, softDrink have a value, unwrap it and put it in the drink constant, then display its value.”

Implicitly Unwrap Swift Class File Instance Variables

In a Swift class file, you declare an instance variable as an implicitly unwrapped optional by appending an ! at the end of its type. The compiler implicitly (automatically) unwrap it. Code below shows how to declare an implicitly unwrapped instance variable called outputTextView.

@IBOutlet weak var outputTextView: UITextView!

Implicitly unwrap Swift Class file Parameters

A Swift class file method parameters are implicitly unwrapped optionals. For example, here is the application:didFinishLaunchingWithOptions: method that’s automatically added to the AppDelegate class for you:

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
  // Override point for customization after application launch.
  return true

As you can see, the application and launchOptions parameters have an ! after the type, indicating that they are implicitly unwrapped optionals. This allows you to access the values these parameters contain without unwrapping them.

Inc conclusion, optional is a great feature of Swift that allow you to safely handle nil variables in your iOS application.