What is an Optional in Swift, and what is it internally?
Predict first
What does this print?
let x: Int? = nil
print(x == Optional<Int>.none)
- true
- false
- Compile error
Mental model. An Optional is a labelled box with exactly two states: “empty” and “here is the thing”. It is not a magic null.
Optional<Wrapped> is a plain generic enum with two cases: none and some(Wrapped). Int? is sugar for Optional<Int>, and nil is just Optional.none.
Because it is an enum, you can pattern-match it, switch on it, and it is fully typed. Unlike Objective-C nil, which is a null pointer that silently accepts messages, a Swift optional forces you to unwrap before use.
nil is just the literal for .none. They are the same enum case.
Common traps
- “
nilis a null pointer.” For class optionals the compiler usually does use the null pointer representation as an optimization, but semantically it is still the.nonecase. - “Optionals are free.” An
Int?needs extra storage for the tag;String?does not fit in one word. The layout is not guaranteed either.
They might follow up with
- What is the memory layout of
Bool?orInt?? It is an implementation detail — the compiler may use spare bit patterns or padding, and it has changed between Swift versions. - Why can you switch on
niland.sometogether? Because both are enum cases of the same type;nilis a literal for.none.
Related questions
- 1.2.3 if let vs guard let vs ?? vs force unwrap — when is each one OK?
- 1.2.2 Why can switch on an Optional use .none / .some and also nil?
Why can switch on an Optional use .none / .some and also nil? →