However, Swift has to work with a lot of Objective-C code and design patterns2 where variables can and are often set to nil. That’s where optionals come in. Optionals are protective wrappers around your variables. The wrapper itself tells you whether or not the variable within is set to nil, but that’s all it says. If the variable inside isn’t nil, and you want to access it, you have to unwrap the optional.
Defining an optional is easy, just add a
? to the end of your variable name.
Accessing an optional is a bit trickier, and you have a few alternatives you can use depending on the situation.
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 you’re absolutely sure the value should be there, you can force unwrap the optional by appending a
! to the variable.
If the value is actually nil, your program will crash.
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.
Swift optionals can be a bit confusing3, and a lot of other people have tried to explain them:
I wrote this post to cement my own understanding of optionals. ↩