Working with Optional Variables in Swift

One unique feature of Apple’s Swift programming language is the use of optional variables, where a variable can either hold a value or not. The problem with optional variables is that you have to use them by first checking if they have a value or not.

The simplest way is to just check to see if the optional variable is not equal to nil. If it’s not equal to nil, then you can use the optional variable.

To access the value stored in an optional variable, you have to unwrap it using the exclamation mark like this:

var age : Int?

age = 12

// Example #1 - != nil
// 1. Check if an optional variable is not nil
// 2. Then unwrap it using the exclamation mark !
if age != nil {
    print ("The age = \(age!)")
} else {
    print ("Age is undefined")
}
Checking if an optional variable is not nil

The problem with this method is that you have to remember to use the exclamation mark to unwrap the optional. If you omit the exclamation mark, your code won’t work properly. Instead of getting an actual value, you’ll get something that looks like this: Optional(value) where “value” is a number or string, depending on what type you defined the optional variable to be.

A second way to access the value stored in an optional variable is to set another variable to the value of the optional variable. If this other variable is not nil, then the optional variable must contain a value:

var age : Int?

age = 12

// Example #2 - if let
// 1. Set another variable equal to the optional variable
// 2. If it has a value, then use that value
if let x = age {
    print ("The age = \(x)")
} else {
    print ("Age is undefined")
}
Using if-let to retrieve a value from an optional variable

Yet a third way to access optional variables is to use a function with a guard statement. A guard statement basically acts like a filter. First it sets another variable equal to the optional variable. If the optional variable is nil, the guard statement immediately runs code to deal with this nil value. Otherwise, the guard statement allows the rest of the code in a function to run like this:

var age : Int?

age = 12

// Example #3 - guard let
// 1. Set another variable equal to the optional variable inside a functioin
// 2. If it has a value, then use that value

func testMe (number: Int?) {
    guard let x = number  else {
        print ("Age is undefined")
        return
    }
    print ("The age = \(x)")
}

testMe (age)
Using a guard statement to check for a nil value in an optional variable

These three ways all let you work with optional variables so choose the way you like best. The guard statement may look odd but it may actually be the best way to check for a nil value in an optional variable.

The if-let method may be the second best way to access optional variables and the != nil method may be the clearest but the least preferred method since it’s slightly clumsier.

No matter which method you use, they’ll all work so use the way you prefer and just make sure you always keep track of your optional variables.

April 19th, 2016 by
HTML Snippets Powered By : XYZScripts.com