iAchieved.it

Software Development Tips and Tricks

By

A Morning with Swift Optionals

Swift optionals come off as a bit weird. There, we said it. Those familiar with Scala, F#, Haskell, or Rust might disagree, but then again, how many people do you know that actually program in Haskell? And we can guarantee you that 90% of Objective-C programmers out there are not working with these functional programming languages. At any rate, optional types have been introduced to the programming language that will be the flagship for iOS and OS X development in the future. It’s time to get on the bandwagon.

At the core optionals are conceptually easy to understand. An optional type is simply a way of saying that this object here might be of type X. Or it might not. In Swift there are two concrete possibilities (or options): it is either the type it was declared as, or nil. It cannot be some other type. An illustration:

In this example the object to which the currentTemperature variable refers can either be a Double, or nil. So, let’s say in our code we use some API to go retrieve the current temperature, and that API has declared a function like this:

The Double? again signifies that the return value will either be a Double or nil. How would you interact with this function? What if we just did:

Swift complains and says “Value of optional type ‘Double?’ not unwrapped; did you mean to use ‘!’ or ‘?’?” Now don’t tell us that the first impression of someone with a Ruby, Python, or even Objective-C background wouldn’t be to look at that and say, huh, what? Unwrapped? Like a Chipotle burrito or Snickers bar? I don’t get it.

What Swift is saying is “Hey pal, look here. You presented me with a Double variable to capture the return value from a function that may return a Double or nothing. If you really mean it you are going to have to decide whether you want to insist that you will receive a Double or you’ll have to change your variable type.”

The first option, using !, forces what is known as unwrapping, which we liken to casting (but it’s not really). It’s sort of like a declaration that “we know this a Double so use it as one.” If it isn’t actually a Double and is truly nil you’re going to get a crash. Which is actually good if you think about it… we want errors in logic to crash and burn so we can catch them before we ship our software.

Typically however you would not code by throwing exclamation marks around (well, sometimes we do if we’re chasing down an elusive bug). In practice we’ve found ourself only using ! when the application logic is (supposedly) guaranteeing a certain condition, but we prefer the defensive programming approach which substitutes “trust but verify” with “verify”. Swift provides a syntactical construct called optional binding that is done like this:

This is logically equivalent to the following Objective-C code:

Just keep in mind that a Swift nil is not the same as Objective-C’s nil. Quoting Apple, “Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.”

In working with Swift we’ve found that deferred initialization of object members require you declare them as optional types. For example:

The Swift compiler responds, error: property 'self.radius' not initialized. Now it might not make much sense to have a Circle with no radius, but let’s use our weather example. We could reasonably have nothing for our temperature. Zero as a value won’t suffice to signify such a situation (alliteration is fun), nor will negative values. We really do want to be able to declare a variable that could have no temperature. Here we have created a Weather class that has a temperature of type Double?. This allows those obtaining the temperature to understand that it might be undefined.

Before we wrap up this little exposition on Swift optionals, let us say this: you will be well served by spending time with Swift optionals and what unwrapping is and what the ! and ? symbols mean. Our time with iOS 8 and Swift has shown that usage of optionals is significant and that failure to understand them will be a hindrance. And we haven’t even done a deep-dive on optional chaining (next post perhaps), but it too will be a significant part of iOS and OS X programming.

Leave a Reply

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