---
title: "#173: Swift Optionals - Under the Hood 🚗"
url: https://littlebitesofcocoa.com/173-swift-optionals-under-the-hood
author: Jake Marsh
published: 2016-01-20
topics: ["Swift","Under the Hood"]
description: "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..."
---

# #173: Swift Optionals - Under the Hood 🚗

By Jake Marsh, January 20, 2016. HTML: https://littlebitesofcocoa.com/173-swift-optionals-under-the-hood

_Optionals_ in **Swift** are a great way for us to represent <i>either</i> some value, or <i>no value at all</i>. 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 <i>"Optional"</i>:

``` swift
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:

``` swift
String?
```

is simply a shorthand way of writing:

``` swift
Optional<String>
```

**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**.

``` swift
/// ...

public init()

public init(_ some: Wrapped)
```

The first `init` statement handles **Optionals** with <i>no value</i>, the second handles the presence of some value. Additionally, **Optional** adopts **NilLiteralConvertable**, so all three of these **statements** mean the same thing:

``` swift
let foo: String? = nil
let foo = Optional<String>()
let foo: String? = .None
```

Similarly, these are also the same:

``` swift
let foo: String? = "Hello"
let foo = Optional<String>("Hello")
let foo: String? = .Some("Hello")
```
