Sobes.tech
Middle+

How are optionals stored in memory?

sobes.tech AI

Answer from AI

Optionals in Swift are represented as an enumeration with two cases: .none (or nil) and .some(Wrapped).

enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

When an optional contains a value (.some(Wrapped)), it stores the value of type Wrapped along with an additional bit indicating the presence of a value. If the optional is nil (.none), only this bit or a special byte pattern indicating absence of a value is stored.

The storage method can vary depending on the type Wrapped and the processor architecture (32-bit vs 64-bit), but the general idea is to use some indicator of value presence. For reference types, for example, nil can be represented as a null pointer, when no indicator is needed or it is combined. For value types, additional space for an indicator is required.

Example with 64-bit architecture and an indicator:

  • If Optional<T> contains a value: memory for T + 1 bit (or byte) for the "has value" indicator.
  • If Optional<T> is nil: usually a special byte pattern is stored or combined with a pointer for reference types.

It is important to note that for types smaller than their natural alignment (e.g., Bool on a 64-bit system), the indicator of presence can be "embedded" in the remaining bits, saving memory. This optimization is called "Nullable Pointer Optimization" for reference types and is similar for some value types.

How are optionals stored in memory? — iOS - sobes.tech