Active Filters: Under the Hood

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 Optional enum in the Swift headers. We can get here by pressing ⌘⇧O, then typing "Optional":

public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
  case None
  case Some(Wrapped)
  // ...

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:


is simply a shorthand way of writing:


Swift enums 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.

/// ...

public init()

public init(_ 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:

let foo: String? = nil
let foo = Optional<String>()
let foo: String? = .None

Similarly, these are also the same:

let foo: String? = "Hello"
let foo = Optional<String>("Hello")
let foo: String? = .Some("Hello")