Nil in an optional type, what exactly is behind it? what does he look like in memory?

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

var john: Person?

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

An instance of a class stores its value in heap space and stores the link on the stack. (Correct me if I am wrong) johnin this case is an optional optional variable, it does not refer to any instance yet.

Question: Where does the computer store the name string "john"? Is it already created and stored on the stack and is waiting for a link to some instance on the heap ? And where is the value zero stored?

Many thanks

+4
2

var john: Person?

Stack.

- Optional Person

Optional<Person>

Optional.none.

john = Person(name: "Mr Robot")

Heap.

Person initializer.

. Optional.none Optional.some, Person .

+2

enum :

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

nil Optional.none. , john ; , , . , Person - , , " " . , .

:. enum Person . , , , Person.

+3

All Articles