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
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.
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.
Behind the scenes, optionals are actually just generic enum
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With