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 .
john
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
var john: Person?
Stack.
Stack
- Optional Person
Optional
Person
Optional<Person>
Optional.none.
Optional.none
john = Person(name: "Mr Robot")
Heap.
Heap
Person initializer.
Person initializer
. Optional.none Optional.some, Person .
Optional.some
enum :
enum
enum Optional<T> { case some(T) case none }
nil Optional.none. , john ; , , . , Person - , , " " . , .
nil
:. enum Person . , , , Person.