Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 360
SLN Avatar asked Jul 13 '16 15:07

SLN


2 Answers

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.

like image 169
Luca Angeletti Avatar answered Oct 11 '22 07:10

Luca Angeletti


Behind the scenes, optionals are actually just generic enums with associated values:

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

nil is just shorthand for Optional.none. So in your example, john has all the storage it needs already; it's set to a value, that value just happens to represent nothingness. Now, since Person is a class, which is a reference type, "all the storage it needs" is actually just room for a pointer. The storage for your instance's properties will be created on initialization, as for all class instances.

In conclusion: There's memory for an enum with an associated pointer to a Person at first. Then, after you initialize the variable, there's of course a Person instance as well.

like image 39
andyvn22 Avatar answered Oct 11 '22 08:10

andyvn22