class Person { var name: String init(name: String) { self.name = name } } let person1 = Person(name: "Alice") let person2 = person1 person2.name = "Bob" print(person1.name)
In Swift, classes are reference types. Assigning person1 to person2 means both refer to the same object. Changing person2.name changes the name for person1 as well.
class Counter { var count = 0 } let c1 = Counter() let c2 = c1 c2.count += 5 print(c1.count)
Since Counter is a class, c1 and c2 point to the same object. Increasing c2.count changes c1.count as well.
class Number { var value: Int init(value: Int) { self.value = value } } func doubleValue(_ num: Number) { num.value *= 2 } let n = Number(value: 5) doubleValue(n) doubleValue(n) print(n.value)
The function doubleValue doubles the value property each time it is called. It is called twice, so starting from 5: first call makes it 10, second call makes it 20. The print statement prints 20.
Option C correctly explains that classes are reference types, so the same instance is modified twice.
class Box { var content: String init(content: String) { self.content = content } } var box1 = Box(content: "Apple") var box2 = box1 box2.content = "Orange" print(box1.content)
Both box1 and box2 refer to the same Box instance. Changing box2.content changes box1.content as well.
class Engine { var horsepower: Int init(horsepower: Int) { self.horsepower = horsepower } } class Car { var engine: Engine init(engine: Engine) { self.engine = engine } } let engine1 = Engine(horsepower: 150) let car1 = Car(engine: engine1) let car2 = car1 car2.engine.horsepower = 200 print(car1.engine.horsepower)
Both car1 and car2 refer to the same Car instance. The engine property is also a class instance shared by both. Changing car2.engine.horsepower changes car1.engine.horsepower.