swiftdebuggingmemory-address

Printing a variable memory address in swift


Is there anyway to simulate the [NSString stringWithFormat:@"%p", myVar], from Objective-C, in the new Swift language?

For example:

let str = "A String"
println(" str value \(str) has address: ?")

Solution

  • Swift 2

    This is now part of the standard library: unsafeAddressOf.

    /// Return an UnsafePointer to the storage used for `object`.  There's
    /// not much you can do with this other than use it to identify the
    /// object
    

    Swift 3

    For Swift 3, use withUnsafePointer:

    var str = "A String"
    withUnsafePointer(to: &str) {
        print(" str value \(str) has address: \($0)")
    }