What Are “Optionals”? | Swift Basics Tutorial

What Are SWIFT Optionals? Featured Photo

In this iOS tutorial SWIFT Optionals, we’re going to show you what optionals are and how to use them through some great examples.

Why does Swift have all these cumbersome exclamation points and question marks? What does it all mean? If you’ve happened upon the Swift language even once you’ll immediately notice the use of such symbols all over the code.

You migh be interested in 5 FREE ways to become SWIFT Developer

What is an optional?

At the granular level is an enum with two cases: ‘Some’ or ‘None.’ Let’s look at the following example:

Note that T is essentially the associated value of the type we’re working with.

enum Example {
    case .None
    case .Some
}

Fairly familiar, right? But while the optional shares characteristics of the enum, as noted in the Apple documentationoptionals are a separate type and not an augmented standard type.

So why are optionals useful?

And why do we use them in Swift? The answer lies in their clarity. Ironically, despite using the question mark symbol to represent itself, the optional makes our code quite clear. As described in Apple’s Swift Programming Language text “an optional says,

-> There exists a value, such that it equals ‘x’

or

-> There does not exist a value”

You use an optional in a case where a value may be absent. This may seem strange at first until you take a moment to think about the greater meaning of Swift and its philosophy. Swift is an opinionated language, and as we’ve heard in countless WWDC talks before, Swift is a language that focuses—and prides itself—on safety. Optionals decrease complexity and unify representations of “nothingness” in our code.

Objective-C And Optionals

If you have programmed in the iOS world for a certain length of time and used Swift’s predecessor, Objective-C, you’ll likely recall that the concept of the optional does not exist in C or Objective-C. The closest thing that resembles an optional is Objective-C’s ability to return an object that is nil from a method that in any other circumstance would return an object. In the case where Obj-C returns nil, it means that there exists no valid object. This, however, only applies to objects. This does not apply to basic C-types, structs, or even enumerations. In other words, primitives are left out in the cold and their value can return anything.

In those instances, Obj-C returns a special value known as NSFound. While NSfound may mark a variable as valueless, the downside is that it assumes the method caller remembers that there is a special value to test against. Ultimately it adds a layer of unnecessary complexity. And worse, if you don’t remember to manually include a value to test against, you risk your app crashing.

Swift accounts for this complexity via the keyword let. With ‘let’, you indicate the absence of a value for any type at all without the need for special constants.

Simplicity

This is where the power of the optional then comes into play. Because we can deal with any object. We no longer need to consider for special circumstances—which takes away a layer of complexity. Either the object exists or is nil. No strange third circumstance to account for.

To see this concept in action, create an optional in playgrounds and observe its returned value in the console. If all goes well you’ll see Optional(your value here).

So when would we see this being useful? Think of whenever you might have implemented a separate BOOL to track if a value has actually been set OR if it’s in the default state you set. In this case, Optionals are of obvious help because they can tell you immediately what’s happened to the BOOL.

The optional is further exotified by its use of a concept called “wrapping”. Wrapping is ultimately a structure. Any actual content or value cannot be accessed until its optional is unwrapped.

Why is this so hard to understand?

The usual reason: programmers poor way of describing things.

Once you realize that Optionals are their own distinct type AND that unwrapping them means dealing with their enum based structure, then the process of “wrapping” and “unwrapping” (again, something I’ll cover later), quickly make sense.

In conclusion, if you liked this iOS tutorial SWIFT Optionals, take a look at some of our other stuff at the tutorial section.

Recommended for you [SWIFT] How to add In-App Purchases in your iOS app

Leave a Reply

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