JuniorCodeCommonNot answered yet
Predict the output when a copied struct variable is mutated
Read the program. A struct value is assigned to a second variable, which is then mutated.
struct Point { var x = 0 }
var a = Point()
var b = a
b.x = 10
print(a.x)
Determine the output of print(a.x) and explain why.
It prints 0. Assigning var b = a copies the value, so b is an independent copy; mutating b.x changes only that copy and leaves a unchanged. A struct is copied on assignment, not shared.
- ✗Expecting the second variable to alias the first rather than copy it
- ✗Thinking a
structassignment shares storage like aclass - ✗Assuming the copy is lazy enough to leak later mutations back
- →How would the output change if
Pointwere aclass? - →At what moment is the value actually copied during
var b = a?
It prints 0. var b = a copies the value, so b is an independent copy. Mutating b.x = 10 changes only the copy; a is untouched:
struct Point { var x = 0 }
var a = Point()
var b = a // value copy
b.x = 10 // only b changes
print(a.x) // 0
Value types are copied on assignment, so a and b have independent storage.