What is a Swift optional 1/28/15
By default all Swift variables must contain a value of the specified type
var bestCaptain:String = "Sisko" // this works
bestCaptain = nil // throws an error
However, Swift has to work with a lot of Objective-C code and design patterns
Defining optionals
Defining an optional is easy, just add a ?
to the end of your variable name.
var myOptional:String? = "I'm an optional, short and stout"
myOptional = nil // totally legal
Accessing optionals
Accessing an optional is a bit trickier, and you have a few alternatives you can use depending on the situation.
Optional binding
The safest way to access your optional value is with optional binding. In optional binding, you assign the optional value to a constant if the optional value is not nil.
if let unwrappedOptional = myOptional {
print("\(unwrappedOptional)")
} else {
print("optional was nil")
}
Forced unwrapping!
If you’re absolutely sure the value should be there, you can force unwrap the optional by appending a !
to the variable.
var myOptionalLowerCase = myOptional!.lowercaseString
print("\(myOptionalLowerCase)")
If the value is actually nil, your program will crash.
Optional chaining?
You can use optional chaining to access properties and methods of the underlying variable by using a ?
. If the variable is nil, those properties and methods are never accessed, and the statement returns nil.
myOptional = nil
print("\(myOptional?.lowercaseString)") // prints nil
More resources
Swift optionals can be a bit confusing
Big thanks to Scott Williams for his valuable feedback on this post. Check out his blog.
-
Non-optional variables can be declared without a value, but can’t be set to nil. Non-optional instance variables need to have a value set in the object’s init method. ↩
-
Objects from the Cocoa libraries often use Implicitly Unwrapped Optionals. ↩
-
I wrote this post to cement my own understanding of optionals. ↩