Optionals in Swift
Optionals are a concept that isn’t in Objective-C, which makes them instantly cool already (and that’s disregarding the usefulness of these, as I’ll go into shortly).
What are optionals?
An optional is a variable with a question-mark (?
) on the end of it. It means that the variable has a value, and it’s X, or that there isn’t a value at all. If you’re from a C# background, you’ll know of the Nullable concept - I believe it’s pretty similar to that. What’s different is that if a variable isn’t an optional it must have a value. The compiler won’t allow you to set it to nil
.
Interestingly, you can use optionals on all types, including primitives and structs, as well as classes, of course.
Under the covers, optionals are just an enum - the question-mark is simply syntactic sugar added by Apple to make them easier to use:
enum OptionalValue<T> {
case None
case Some(T)
}
When to use optionals?
I guess the biggest use for them is that they don’t have to be initialised in a class. Take this example.
class TestClass {
var tableView : UITableView = UITableView()
}
You’ve just instantiated that tableView
property because if you don’t the compiler gives you an error. How frustrating! Instead, you can just do:
class TestClass {
var tableView : UITableView?
}
This essentially says that the tableView can be nil - it has no value at all. If you were to call tableView?.reloadData()
the reloadData method would be ignored if the tableView is nil.
Another good use-case: delegates! One of the most popular design patterns in Cocoa, you can now basically just do delegate?.didDoSomething()
rather than checking if the delegate exists and if it responds to the selector. Amazing.
One thing that should be remembered with Swift is that it aims to be an extremely safe language, meaning it will try and warn you, the developer, at compile time if and when you are doing something that could break. This is the whole point of optionals.
Unwrapping optionals
There is another character that we need to be aware of when working with optionals, and that’s !
. It’s used in the same places as ?
but it’s to be used to unwrap optionals - it exposes the underlying value that the optional is holding. If you know absolutely 100% that the optional is not going to be nil (i.e., it has a value) then you can straight up unwrap it. If not, unwrapping it in an if-statement is safest. To do this you would do something like the following:
if let unwrappedValue = optionalValue {
// optionalValue wasn't nil, and now we have unwrappedValue which is definitely not nil - we can use it safely
} else {
// the optional is nil
}