Topics

Topics

Optionals in Swift are a great way for us to represent either some value, or no value at all. Like many parts of Swift, they're actually built (mostly) in Swift itself. Today we'll pop the hood, and take a look at how they work. Let's get started.

We'll begin by heading over to the definition of the Optionalenum in the Swift headers. We can get here by pressing ⌘⇧O, then typing "Optional":

Right away we'll see that Optional types are merely an enum with an associated value. That associated value has a type, but it's a generic placeholder for whatever type we'll make Optional references to. The trailing-? syntax is merely syntactic sugar, for example:

String?

is simply a shorthand way of writing:

Optional<String>

Swiftenums really show their power here, we're able to represent a fairly high level concept, with this relatively simple construct. Next, let's look at initializing Optionals.

/// ...publicinit()publicinit(_some:Wrapped)

The first init statement handles Optionals with no value, the second handles the presence of some value. Additionally, Optional adopts NilLiteralConvertable, so all three of these statements mean the same thing: