SLN SLN - 4 months ago 11
Swift Question

nil in an optional type, what exactly is behind it? what it looks like in the memory?

class Person{
let name: String
init(name: String) {
self.name = name
}
}

var john: Person?


The code snippet above defines a variable of optional type named
john
. At this moment, the variable has an initial value of nil.

A class instance saves its value in the heap space and stores the reference in the stack. (Correct me if I'm wrong)
john
in this case is a un-assigned optional variable, it does not reference to any instance yet.

Question: Where does the PC stores the name string "john"? Has it already been created and stored in the stack and waiting for reference to some instance in heap? And where the value "nil" stored?

Many Thanks

Answer

With this

var john: Person?

A slot of memory is added on top of the Stack.

The type of this slot is Optional value of type Person

Optional<Person>

Inside this location of memory we found the Optional.none value.

After this

john = Person(name: "Mr Robot")

some memory is allocated into the Heap.

This memory is then written following the logic of the Person initializer.

Then let's get back to the Stack. Here the Optional.none is replaced with the value Optional.some and the address memory of the Person object is written inside a special a field of the enum value.

Comments