Swift Language Overview - Why Optionals?


Example

Often when programming it is necessary to make some distinction between a variable that has a value and one that does not. For reference types, such as C Pointers, a special value such as null can be used to indicate that the variable has no value. For intrinsic types, such as an integer, it is more difficult. A nominated value, such as -1 can be used, but this relies on interpretation of the value. It also eliminates that "special" value from normal use.

To address this, Swift allows any variable to be declared as an optional. This is indicated by the use of a ? or ! after the type (See Types of optionals)

For example,

var possiblyInt: Int?

declares a variable that may or may not contain an integer value.

The special value nil indicates that no value is currently assigned to this variable.

possiblyInt = 5      // PossiblyInt is now 5
possiblyInt = nil    // PossiblyInt is now unassigned

nil can also be used to test for an assigned value:

if possiblyInt != nil {
    print("possiblyInt has the value \(possiblyInt!)")
}

Note the use of ! in the print statement to unwrap the optional value.

As an example of a common use of optionals, consider a function that returns an integer from a string containing digits; It is possible that the string may contain non-digit characters, or may even be empty.

How can a function that returns a simple Int indicate failure? It cannot do so by returning any specific value as this would preclude that value from being parsed from the string.

var someInt
someInt = parseInt("not an integer") // How would this function indicate failure?

In Swift, however, that function can simply return an optional Int. Then failure is indicated by return value of nil.

var someInt?
someInt = parseInt("not an integer")  // This function returns nil if parsing fails
if someInt == nil {
    print("That isn't a valid integer")
}