Sobes.tech
Middle+

How is an optional stored in memory in Swift?

sobes.tech AI

Answer from AI

Optional in Swift is stored in memory in one of two ways:

  1. For types that do not conform to the _ObjectiveCBridgeable protocol: Small/Large Optional Representation.

    • Small Optional: If the size of the value is less than or equal to the size of a pointer, Optional adds one byte to the type size to store a flag (Present/Absent).
    • Large Optional: If the size of the value is larger than the size of a pointer, Optional uses two "slots" in memory: one for the value itself (if present) and one for the presence flag. These can be either two adjacent memory segments or, in more complex cases, a reference to a heap-allocated value.
  2. For types that conform to the _ObjectiveCBridgeable protocol (e.g., classes, some structures): Nullable Pointer Representation.

    • If the type is a class or can be represented as an Objective-C pointer, Optional uses the fact that a pointer can be nil. In this case, nil Optional is represented as a null pointer, and a non-nil Optional as a pointer to an object. This is more memory-efficient as it does not require an additional flag.

In the end, Optional can occupy either slightly more space than the base type (Small/Large Optional) or as much as a pointer (Nullable Pointer). The specific representation is determined by the compiler based on the type and its ability to be represented as a nullable pointer.

// Example: Int is not _ObjectiveCBridgeable, uses Small/Large Optional
var maybeInt: Int? = 10 // Might be Small Optional

// Example: String _ObjectiveCBridgeable, might use Nullable Pointer
var maybeString: String? = "Hello" // Might be Nullable Pointer

// Example: Protocol (Any) is not _ObjectiveCBridgeable, uses Small/Large Optional
var maybeAny: Any? = 5 // Small/Large Optional
How is an optional stored in memory in Swift? — iOS - sobes.tech