Understanding Optional Types in Swift

When Swift was introduced at WWDC 2014, one of the features it emphasized was type safety.  

Variables are considered to be non-optional by default.  This means that we have to assign a value to the variable.  Otherwise, the compiler will yell at you.

var title: String
print(title) // Error: variable 'title' used before being initialized

title = "Narcos"
print(title) // Narcos

What is an Optional type?

An Optional type has either a value (Int, String, etc) or no value at all (nil).   We use a question mark to declare a variable as optional.   

var firstName: String? = "John"
var middleName: String?
print(middleName) // nil



Why are Optionals useful?

Optionals allow us to discover potential issues at compile-time and prevent unexpected run-time errors and crashes. 

Unwrapping Optionals

Here we declare an optional String and try to use the variable in another expression. 

var name: String?
name = "Francis Ford Coppola"
var output = name + " is a director" // Error: value of optional type 'String?' not unwrapped

We get an error about the value not being unwrapped.   Why?  The concatenation operator (+) wants a String and not an Optional.   So how do we fix this?  

We can use an exclamation mark to explicitly "unwrap" the optional to a String.

var output = name! + " is a director"

We unwrapped the optional so we could use it in a concatenation expression.   The risk with using the exclamation mark is that it forces an optional to be unwrapped regardless of the consqeuences.  If the optional was nil, then we would get a run-time error.

What if we did not know whether the director variable had a value?  We could check its value before using it:

if name != nil { 
  var output = name + " is a director"

Optional Binding

Optional binding is a convenient shorthand that checks for a nil value and handles unwrapping.

if let name = name { 
  var output = name + " is a director"