Introduction to Swift: Optionals

An optional variable is a variable which has either a value or has no value at all. Optionals are designed in Swift, with type-safety in mind. Swift's optionals provide compile-time check that would prevent programming errors in run-time. You can follow this tutorial using Playgrounds with Xcode 6.

When declaring variables in Swift, they are non-optional by default, which means the value can't be nil.

var name:String = nil
// compiler error

To make it possible to assign a nil value to a variable a question mark must be added to the type to make it an optional variable.

var name:String? = nil
// OK

// the nil assignment can be omitted with optionals
var name:String?

With optionals you can check the value for nil and catch the error at compile-time instead of run-time. Consider the following example.

func findName(name: String) -> String?
{
  if name == "Tom" {
    return "Tom"
  } else if name == "Jim" {
      return "Jim"
    }
  
  return nil
}

var name:String? = findName("Jack")
let friend = "My friend is " + name
println(friend)
// Compiler error

To test if the name value contains nil or not we can make use of unwrapping the optional variable. In other words, we tell the compiler the optional must contain a value. Unwrapping an optional is done by adding an exclamation mark at the end of the optional variable.

var name:String? = findName("Jack")
if name {
    let friend = "My friend is " + name!
    println(friend)
}

To manually test each optional and unwrap it can be quite cumbersome, so instead of force unwrapping we can make use of optional binding. This is another kind of checking the optional, if it contains a value it will be unwrapped and put in a temporary variable.

var name:String? = findName("Jack")
if let tempName = name {
  let friend = "My friend is " + tempName
  println(friend)
}

There is no need to unwrap the tempName variable, because it is not an optional. The code can be simplified by putting the function evaluation inside the if statement.

if var name = findName("Jack") {
  let friend = "My friend is " + name
  println(friend)
}

This finished this part of the introduction serie of Swift programming