Sobes.tech
Junior — Middle

Does instant copying of reference type objects occur when they are assigned?

sobes.tech AI

Answer from AI

In programming languages with memory management, such as Swift or Objective-C, assigning a reference type variable copies the reference, not the object itself. That is, the object is not copied instantly; instead, both variables start pointing to the same object in memory.

For example, in Swift:

class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

let person1 = Person(name: "Alice")
let person2 = person1 // Copies the reference, not the object
person2.name = "Bob"
print(person1.name) // Will output "Bob" because person1 and person2 refer to the same object

Thus, there is no instant copy of the object; only the reference to it is copied.

Does instant copying of reference type objects occur… - sobes.tech