I'm trying to gain a deeper understanding of how Swift copies value types:
The behavior you see in your code will always be as if a copy took place. However, Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so.
To advance my understanding, I'd like to get the memory address of a value type. I tried unsafeAddressOf(), but this doesn't work with structs and it seems to cast Swift's standard library types to reference types (e.g. String is cast to NSString).
How can I get the memory address of a value type, like an instance of Int, or a custom struct in Swift?
According to Martin R' s answer
According to nschum's answer, you can get the (stack) address of a struct, build-in type or object reference like this:
One thing I found is, if
myStruct
has no value, the address will be retain same:I'm not sure if there's a "recommended" way to do that, but one method is to use
withUnsafePointer(_:_:)
, like this:This printed
0x00007ffff52a011c8
on my machine.Swift 2.0 :
You can use this
unsafeAddressOf(someObject)
or in Swift 3.0:
use
withUnsafePointer(to: someObejct) { print("\($0)") }