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:
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:
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:
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.