Lesson 009 – Intro to Optionals

OptionalsSo far, we’ve come up against Optionals a few times in our lessons. As we do more and more with UIKit and our iOS apps, we will see it more and more. It is especially prevalent when talking to services and trying to deserialize JSON. We will need to have a certain level of understanding before we get there.

Introduction to Optionals

At its core, the idea is very simple. Swift Optionals are essentially nullable/nillable types from other languages. Reference types can be null or nil (depending on the language), but value types cannot. What that means is that you can’t (again, in many languages) have a null integer or null boolean. What many people would do instead is create some sort of stand-in value that would represent the “lack of” an input. Maybe a 0 or a -1 for an integer would mean that no value had been set. But, for booleans we are left in the dark. Does false mean the person chose not to set it, or just hadn’t set it yet?

That is why other languages created nullable types, to specify that no value had ever been set. In Swift, we can create these types by using the question mark operator, ?. But, this gives us a weird behavior when we try to use it.

This actually makes a little more sense when you consider that the Int? syntax is actually shorthand. What we are actually doing is this

When you see it like that, it makes a little more sense that the value is Optional(7). We basically declared an Optional box and told Swift we could only store either Integers or nothing in that box. So, when we ask for the value, Swift tells us exactly that information. How do we get the value all by itself? We use an exclamation point, like this:

What will happen if there is nothing in the Optional (nothing in the “box”) and we use the exclamation point?

In this case, Swift has a fit and tells us fatal error: unexpectedly found nil while unwrapping an Optional value.

Safely Unwrapping Optionals

So, how can we handle this issue? Fortunately, Swift has a special syntax to help us called if let. We use it like this

This syntax is special in that it lets us try to get the value from an Optional. If the value from the Optional is nil, the if statement evaluates as false and we skip the if block and go to the else block (if it is present). If let is limited to working with Optionals, though. You can’t use it on other types. Both of these statements fail with the error error: initializer for conditional binding must have Optional type, not ‘Int’

You might be thinking to yourself, of course it doesn’t work. You aren’t evaluating anything to true. I bet it works with a Boolean! Unfortunately, that doesn’t work either.

This code errors, too, with the message initializer for conditional binding must have Optional type, not ‘Boolean’. If let – while handy – is only for Optionals.

Setting Sensible Defaults

What if you are processing these values, but you want to set them to a sensible default? Meaning, if we are processing data back from a web service and we get a nil, maybe we want to treat that like a false value or a blank string when we show it to the UI. In those cases, you have two major options. The way to do it is to declare another variable that you will actually use and set its value based on the incoming variable. We can do that two ways. The first way is to use the else portion of the if let.

The other way is to use Swift’s coalesce operator, ??. In this case, since the Optional is nil, Swift will just use the value after the ??

Conclusion

Hopefully, this lesson will give you a little better idea what Swift is doing when we encounter Optionals. As I mentioned earlier, we are going to see these most of all when dealing with web service calls or when dealing with UI controls within iOS. Now, we’re a little more prepared to deal with those. Don’t forget that you can find the source code to these lessons on GitHub.

Add Comment

Required fields are marked *. Your email address will not be published.