Want to Drive Innovation through Crowdsourcing? Learn the 5 Steps Get the eBook ×

A #Swift Series Part 2 – Shakespearean Optionals

By wwwtc In Uncategorized

Posted July 10th, 2015

A long time ago, when I was just a young high schooler sitting in my English class, I came across Hamlet bemoaning the pain of his existence in his titularly-titled Shakespeare play. “To be or not to be!” he cried, weighing the heaviness of being against the light but uncertain nature of nothingness.

While we’re certainly not going to deal with any existential crises today (or deal with errant syntax, as I touched upon in part one), I do think Hamlet’s soliloquy provides a good platform to talk about a topic in Swift that I’ve been mulling quite a bit recently: optionals.

Basically, optionals are a type that is used to represent the value of nothing in Swift. This value is referred to as “nil.” When variables are normally declared, they are not of the optional type, which implies that they have a non-nil value. In Shakespearean terms, they are. They’re the “be” of Hamlet’s great indecision. Who knew Hamlet was referring to programming hundreds of fictional years before the language was even invented? I sure didn’t.

Anyways, that’s the basic nature of nil within optionals. In application, however, it’s not as simple as just a value that indicates nothingness. Let’s say you want to craft a function to divide up a dinner bill between the number of people who showed up. Here’s an example of what the function would look like:

The function works just fine. A $100 dollar bill (drinks cost a lot – you were in Seattle when Wilson threw that interception) split between you and four other friends amounts to $20 per person. Easy math.

But what if you accidentally punch in a negative number? Then this happens:

Not too bad. No horrific crashes or anything. But we don’t want to return a negative number, because then the restaurant may call the police if you attempt to tell them that they actually owe each of you $20 dollars.

Here’s where optionals come in handy. Now, we don’t want to return an inaccurate figure. Rather, we want to return a nil value so we don’t try to extort anyone. With a little alteration to the formula, we now get:

Works like a charm. Now, if we split the bill between five people, we get $20 dollars each. And if we accidentally punch in a negative number, a nil value is returned. Note the question mark when we return the value now – it says “Int?” The question mark tells us that there may be a value returned, or nothing may be returned at all. To nil, or not to nil, as Hamlet might wonder.

We’re actually not finished yet, though. Turns out, you forgot the tip. Since you’re legendarily cheap, you can only tip a dollar (jeez):

An error pops up (ignore the fact that the correct figure was actually returned – Swift isn’t happy with what you’ve done)! We need to see if there’s actually a value present. Because optionals can be a value or a nil, we need to check to see what the value was, or “unwrap” it.

To Swift, this is like Schrodinger’s Cat, except I guess in Swift-speak, it would be Schrodinger’s Jolly Rancher (is anything even there if you unwrap it?) There may yet be a value, but because Swift doesn’t know what we know, we need to be extra-specific. Note the suggested “!” sign after “billSplit(100, 5)” – that’s the bang operator, and that forcibly unwraps variables (or in our case, the result of the function). When applied, we get:

Wonderful. Now the waitress is mad as hell, but at least you got your function to work correctly. Swift is happy, and that’s all that matters, right?

What we did up there with the bang operator is called forced unwrapping. Generally, you only want to force unwraps if you would be willing to bet your life that there’s a value present. Another way to unwrap a variable in a “safer” manner (without forcing it) would be to use an if-let statement:

With the if-let, we’re checking to see if it exists, and then assigning it to a constant. Try putting a negative number into billSplit() and see what happens.

For now, that’s all of my insights and opinions. I still have much to learn, so I have to get back to that so I can make sure I write all of this for you guys. Thanks for reading. Stick around for the next installment if you’d like, or don’t. But if you don’t, you best be learning Swift instead.