[swift-users] Memory Address of value types and reference types

somu subscribe somu.subscribe at gmail.com
Tue Sep 12 07:43:32 CDT 2017


Hi,

I would like to know the correct way to get the memory address of value types and reference types.

Given below are the attempts made.

class C {}
struct S {}

let c1 = C()
var s1 = S()
var s2 = s1

//Reference type:
print("c1 address: \(Unmanaged.passUnretained(c1).toOpaque())") //Is this correct ?

//Value type:
withUnsafeMutablePointer(to: &s1) {
    print("s1 address: \($0)")
}

withUnsafeMutablePointer(to: &s1) {
    print("s1 address: \($0)")
}

//Output:
//c1 address: 0x000060c0000015f0
//s1 address: 0x0000000119027a90
//s1 address: 0x0000000114571880

The address of s1 seems to be different the 2 times it is printed. It seems like my approach isn’t correct.

Tested on:
Swift 4 
Xcode 9.0 beta 6 (9M214v)


Questions:
1. Is the above shown the correct way to get reference type memory address ? If not could you let me know the correct way.
2. What Is it the correct way to get value type memory address ?
3. Is it possible to get the memory address of immutable value type (declared as let)

Thanks and regards,
Muthu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170912/9ccb7823/attachment.html>


More information about the swift-users mailing list