A quick primer on Swift & optionals

Optionals is a new concept in Swift, and for those of us coming from Objective-C, certainly not anything we have heard of before. So what exactly are optionals?

An optional value is denoted by the (?) symobol, with the premise of stating that there may be a value and it equals something or it may not have a value at all. So, if we are not sure something would always return a value, we classify it as an optional, as follows:

var aVariable:String? = notAlwaysAValue

The variable therefore could either have a value or be nil. Remember, you cannot leave a variable that could possibly be nil naked or exposed, you need to always declare it as an optional value type. Another thing to note is, in Swift unlike Objective-C, nil is not a pointer to an object that isn't in the memory stack, but rather a lack of any value assigned to it. Usually in a statement, we can combine an optional by setting an assigned constant to the optional:

if let aVariable = notAlwaysAValue{

As you can see, having an if and let allows us to assign a questionable variable to a constant, and then test if it has a value, then do something. This is called optional binding, and it's a great safe way to extract a value but not get too concerned if the value is nil, and cause a run-time exception.

If we know, from the structure of our app that a particular value will always have a value once it is set, without risk of being nil, we can notify the compiler to remove the need to check and unwrap optional values every time it is accessed. This is what is referred to as implicit unwrapping optionals, placing an exlamation mark (!) rather than a question mark (?), after the type.

So, if the optional's value will exist immediately after first definition, and we can assert that it will exist at every point therefater, we can therefore mark it as !. An implicitly unwrapped optional is usually a normal optional behind the scenes, but can be used like a non-optional value without the need to unwrap the optional value each time, if that makes sense. So, here's an example:

let aPossibleValue:String? = "This may not always have something"
let aVariable = aPossibleValue! 

As you can see, we needed to have a ! to unwrap the initial optional variable, because we weren't sure it would always have a value.

let assumedToHaveValueVar:String! = "This will always have a value"
let aVariable = assumedTohaveValueVar

Since we have declared the initial variable as an implicitly unwrapped optional string, even though it may be a string behind the scenes, we can work with it without having to unwrap it in the future, as you can see with aVariable. It is now unwraped automatically whenever it is used. So, as promised, a concise summary explanation of what Optionals are in Swift. Feedback is always welcomed