This question belongs to Swift Programming Language , specifically the domain covering structs, classes, properties, methods, and the difference between structures and classes .
The key point is that Printer is declared as a class :
class Printer {
var copies: Int
init(copies: Int) {
self.copies = copies
}
}
In Swift, classes are reference types . That means when you assign one class instance to another variable, both variables refer to the same object in memory rather than creating a separate copy. Apple’s Swift language guide explains that classes are passed by reference, while structures are value types. So in this code:
var printer1 = Printer(copies: 2)
var printer2 = printer1
both printer1 and printer2 point to the same Printer instance.
Next, this line changes the shared object:
printer2.copies = 10
Because printer2 refers to the same instance as printer1, changing printer2.copies also changes printer1.copies. Therefore, when the code executes:
print(printer1.copies)
the output is 10 .
This question tests one of the most important Swift concepts: classes are reference types , while structs are value types . If Printer had been a struct instead of a class, the result would have been different because assignment would copy the value rather than share the same instance.