Search code examples
swiftmemorymemory-managementswift3

Swift's memory management


I'm a little confused regarding Swift's memory management. Can someone explain to me how come kid1 always stays at the same memory address? Even when I do kid1=kid2 or initialize a new object?

Sample Playground


Solution

  • Your code prints the memory location of the kid1 variable, and that does not change if you assign a new value to the variable.

    If Kid is a reference type (class) then you can use ObjectIdentifier to get a unique identifier for the class instance that the variable references:

    var kid1 = Kid(name: "A")
    var kid2 = Kid(name: "B")
    
    print(ObjectIdentifier(kid1)) // ObjectIdentifier(0x0000000100b06220)
    print(ObjectIdentifier(kid2)) // ObjectIdentifier(0x0000000100b06250)
    
    kid1 = kid2
    print(ObjectIdentifier(kid1)) // ObjectIdentifier(0x0000000100b06250)
    

    The object identifier happens to be the address of the pointed-to instance, but that is an undocumented implementation detail. If you need to convert an object reference to a real pointer then you can do (compare How to cast self to UnsafeMutablePointer<Void> type in swift)

    print(Unmanaged.passUnretained(kid1).toOpaque())