Search code examples
swiftclassreference-type

Why is memory address the same after pointing at new Object?


I have the following set up in a playground and am expecting the last two memory address to be the same. I point person2 to person1 then person1 is reassigned to a new Person so person2 should have the same memory address as person1.

Why does it have the same address as to when we first assign it?

class Person {
  var name = ""
}

var person1 = Person()
print(Unmanaged.passUnretained(person1).toOpaque())
//0x0000600000043ea0

var person2 = person1

person1 = Person()
print(Unmanaged.passUnretained(person1).toOpaque())
//0x00006000000568f0
print(Unmanaged.passUnretained(person2).toOpaque())
//0x0000600000043ea0

Solution

  • That's how reference types work in Swift.

    When you've created person1 it's an instance of the class Person. person1 is then a pointer/reference to a place in the memory that represents that instance.

    Then you instantiate var person2 = person1, so person2 becomes another pointer to the same location in the memory. But they are two different/independant pointers.

    The line person1 = Person() changes the location in memory to which person1 points: a new instance of the class Person. You haven't updated the instance to which person2 points.