Middle
How are value types and reference types stored in memory?
sobes.tech AI
Answer from AI
Value types (struct, enum, tuple) are stored on the stack. A copy of the data is created when assigning or passing to a function.
Reference types (class, func, Closure, Array, Dictionary, Set) are stored on the heap. The stack only stores a reference to the object on the heap. When assigning or passing, only the reference is copied, not the object itself.
Example of a structure (value type):
struct Point {
var x: Int
var y: Int
}
var p1 = Point(x: 1, y: 2) // p1 on the stack
var p2 = p1 // p2 on the stack, a copy of p1
p2.x = 10 // Only the copy in p2 changes
Example of a class (reference type):
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var person1 = Person(name: "Alice") // Person object on the heap, person1 on the stack (reference to the object)
var person2 = person1 // person2 on the stack (another reference to the same object on the heap)
person2.name = "Bob" // The property of the object referenced by person1 and person2 changes
print(person1.name) // Will output "Bob"