Swift打印对象的地址
在Swift
中,我们可以使用withUnsafePointer(to:_:)
函数来获取一个变量的指针,如下代码所示:
var x = 42
var y = 3.14
var z = "foo"
var obj = NSObject()
withUnsafePointer(to: &x) {ptr in print(ptr)}
withUnsafePointer(to: &y) {ptr in print(ptr)}
withUnsafePointer(to: &z) {ptr in print(ptr)}
withUnsafePointer(to: &obj) {ptr in print(ptr)}
// 输出
// 0x000000011a145660
// 0x000000011a145668
// 0x000000011a145670
// 0x000000011a145688
withUnsafePointer(to:_:)
将第一个参数转换为指针,然后将这个指针作为参数去调用第二个参数指定的闭包。如果闭包有返回值,它将作为函数的返回值。
需要注意的是,生成的指针的生命周期限定于闭包内部,不能将其指定给外部的变量。
第二种打印变量的指针的方式如下代码所示:
var x = 42
var y = 3.14
var z = "foo"
var obj = NSObject()
func printPointer<T>(ptr: UnsafePointer<T>) {
print(ptr)
}
printPointer(ptr: &x)
printPointer(ptr: &y)
printPointer(ptr: &z)
printPointer(ptr: &obj)
// 输出
// 0x000000011a145660
// 0x000000011a145668
// 0x000000011a145670
// 0x000000011a145688
参考
- [withUnsafePointer(to:_:)](