O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

For the More Curious: Understanding Optionals

Optionals are a mainstay of all nontrivial Swift programs, and the language has a lot of features that make it relatively easy to work with them. Under the hood, however, there is nothing particularly special about the Optional type. It is a generic enum with two cases:

enum Optional<Wrapped> {
    case None
    case Some(Wrapped)
}

As you probably expect, the None case corresponds to an optional that is currently nil, and the Some case corresponds to an optional that has a value of type Wrapped. Because the Some case is generic, you are able to create optional versions of any type at all.

Most of your interactions with optionals will use optional binding and optional chaining, but you can ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required