Junior
What exactly does a variable store when we create an object of type value?
sobes.tech AI
Answer from AI
When we create an object of type value (structure, enumeration, tuple in Swift), the variable stores a copy of the data of this object directly in memory. Assignment or passing such an object by parameter results in copying its contents.
Examples:
struct Point {
var x: Int
var y: Int
}
var p1 = Point(x: 1, y: 2) // Variable p1 stores a copy of the data (x=1, y=2)
var p2 = p1 // p2 gets a copy of p1's data. These are independent copies.
p1.x = 10 // Only p1.x changes
print(p2.x) // Will output 1, since p2 did not change
Comparison with reference type (class):
| Characteristic | Value Type (structure, enum) | Reference Type (class) |
|---|---|---|
| What is stored in the variable | A copy of the object data | A reference to the object in memory |
| Assignment / Passing | Copying data | Copying the reference (points to the same object) |
| Modification | Affects only the current copy | Affects the object the reference points to (may affect other variables referencing the same object) |