是否有任何方式来模拟[NSString stringWithFormat:@“%p”,myVar],从Objective-C,在新的Swift语言?

例如:

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

当前回答

我对Swift 3的解决方案

extension MyClass: CustomStringConvertible {
    var description: String {
        return "<\(type(of: self)): 0x\(String(unsafeBitCast(self, to: Int.self), radix: 16, uppercase: false))>"
    }
}

这段代码创建的描述类似于默认描述 < MyClass: 0 x610000223340 >

其他回答

斯威夫特2

这现在是标准库的一部分: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

斯威夫特3

对于Swift 3,使用withUnsafePointer:

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

就用这个吧:

print(String(format: "%p", object))

这当然不是最快或最安全的方法。但这对我很管用。这将允许任何nsobject子类采用此属性。

public extension NSObject {
    public var memoryAddress : String? {
        let str = "\(self.self)".components(separatedBy: ": ")
        guard str.count > 1 else { return nil }
        return str[1].replacingOccurrences(of: ">", with: "")            
    }
}

//usage 
let foo : String! = "hello"
Swift.print(foo.memoryAddress) // prints 0x100f12980

其他答案都很好,尽管我正在寻找一种方法来获取整数形式的指针地址:

let ptr = unsafeAddressOf(obj)
let nullPtr = UnsafePointer<Void>(bitPattern: 0)

/// This gets the address of pointer
let address = nullPtr.distanceTo(ptr) // This is Int

只是跟进一下。

@Drew提供的答案只能用于类类型。 @nschum提供的答案只能用于结构类型。

但是,如果使用第二种方法获取值类型为element的数组的地址。Swift会复制整个数组,因为在Swift数组是写时复制,Swift不能确保它的行为一旦它把控制权传递给C/ c++(这是通过使用&来获取地址触发)。如果你用第一个方法,它会自动把数组转换成NSArray这当然是我们不想要的。

所以我发现最简单和统一的方法是使用lldb指令帧变量-L yourVariableName。

或者你可以把他们的答案结合起来:

func address(o: UnsafePointer<Void>) {
    let addr = unsafeBitCast(o, Int.self)
    print(NSString(format: "%p", addr))
}

func address<T: AnyObject>(o: T) -> String{
    let addr = unsafeBitCast(o, Int.self)
    return NSString(format: "%p", addr) as String
}