JuniorCodeCommonNot answered yet
Predict the output when the same program uses a class instead of a struct
Read the program. It is the previous example with class in place of struct.
class Point { var x = 0 }
var a = Point()
var b = a
b.x = 10
print(a.x)
Determine the output and explain what changed versus the struct version.
It prints 10. With a class, var b = a copies only the reference, so a and b point to one instance; mutating b.x changes that object, so a.x reads 10. Reference types share the instance, not copy it.
- ✗Expecting value-copy behaviour from a
classas with astruct - ✗Thinking
var b = adeep-copies the object rather than the reference - ✗Assuming class properties are shared statics across instances
- →How would you get an independent copy of the
classinstance? - →Why does
===now returntrueforaandb?
It prints 10. With a class, var b = a copies only the reference, so a and b point to one instance. Mutating through b changes the shared object:
class Point { var x = 0 }
var a = Point()
var b = a // reference copy, not a value copy
b.x = 10 // mutates the shared instance
print(a.x) // 10
Reference types share one instance, so a write through one name is visible through the other.