There is something I am not understanding about how Swift manages memory address of String(s)
1. Reference types
Here foo
and boo
are 2 pointers to the same memory location.
class Foo { }
let foo = Foo()
let boo = foo
unsafeAddressOf(foo) // "UnsafePointer(0x7FCD13719BE0)"
unsafeAddressOf(boo) // "UnsafePointer(0x7FCD13719BE0)"
Good.
2. Value types
let word0 = "hello"
let word1 = word0
Now word0
and word1
are value types
but here the copy on write
mechanism is involved.
[...] However, Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so. Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimization. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_134
So why do they have 2 different memory addresses?
unsafeAddressOf(word0) // "UnsafePointer(0x7FCD1342ACE0)"
unsafeAddressOf(word1) // "UnsafePointer(0x7FCD13414260)"
3. More
Also please note that String
is a struct
that somehow conforms to AnyObject
.
Tested with Xcode 7 GM Playground and Swift 2.0.