Using Optional Values in Swift

Optional Values

Swift has a nil keyword that is sort of like the None keyword in Python; however, regular variables and constants cannot be nil. In order for a variable to be nil, it must be initialized as an optional. (Constants cannot be nil or optional.) An optional is decalred by appending a question mark the variable type. For example, the two statements below are equivalent.

var x: Int? = nil
var x: Int?

Forced Unwrapping

Declaring a new variable y with the value of x will make y optional also. In order to create a regular variable y that is not optional, we must perfrom a forced unwrapping of x, using the exclamation mark.

var y = x  // declares y as an "Int?"
var y = x! // throws an error b/c x is nil
x = 5      // assign 5 to x
var y = x! // declares y as "Int" with value 5

Optionals in Conditionals and Assertions

One way to check the state of an optional variable is from within an if statement or a while statement.

if x != nil {
    println("x is not nil!")
} else {
    println("x is nil")
}

Another way to check that an optional is, or is not nil is to use an assertion.

var x: Int?
assert( x != nil )

Here, the assertion will fail, and the program will exit.

Optional Binding

Forced unwrapping forces an optional variable to return a regular value. However, if the unwrapped value is nil, then you get an error. Therefore, when using forced unwrapping, you must be sure that the unwrapped value is not nil. This can be done through optional binding, this is where you attempt to bind the optional variable to a new temporary variable in a conditional. If the binding works, the conditional returns True, otherwise if fails and returns false. This can be done with if statements and while statements.

if var tmp = x {
    println("x is not nil!")
} else {
    println("x is nil")
}

Nil Coalescing Operator

We do not always have to wrap optional variables in an if-else structure, we may sometimes be able to use the nil coalescing operator. This operator returns the optional variable if it is not nil, otherwise it returns some value specified by the user. An example,

var x: Int? = nil
var y = x ?? "00"
println( y ) // returns "00"

var u: Int? = 5
var v = u ?? "00"
println( y ) // returns 5

Leave a Reply

Your email address will not be published. Required fields are marked *