In Objective-C, this was as simple as:
[NSString stringWithFormat:@"%p", objRef]
How can I do this in Swift?
func hashString (obj: AnyObject) -> String {
return String(ObjectIdentifier(obj).uintValue)
}
let id = hashString(obj)
Swift 3.0
return String(UInt(ObjectIdentifier(obj))
Swift 4.1
return String(UInt(bitPattern: ObjectIdentifier(obj)))
How about a direct translation:
func pointerToString(objRef: NSObject) -> String {
return NSString(format: "%p", objRef)
}
A more native way (in decimal, not hex):
func pointerToString(objRef: AnyObject) -> String {
return withObjectAtPlusZero(objRef, { ptr in
"\(UnsafePointer<RawByte>(ptr) - nil)"
})
}
func pointerToString(objRef: AnyObject) -> String {
let ptr: COpaquePointer =
Unmanaged<AnyObject>.passUnretained(objRef).toOpaque()
return "\(UnsafePointer<RawByte>(ptr) - nil)"
}
Update: Pointers stringify correctly now, so you can just do
func pointerToString(objRef: AnyObject) -> String {
let ptr: COpaquePointer =
Unmanaged<AnyObject>.passUnretained(objRef).toOpaque()
return "\(ptr)"
}
Swift 4.1
String(UInt(bitPattern: ObjectIdentifier(obj)))
@aleclarson's answer update
func hashString(obj: AnyObject) -> String {
return String(UInt(bitPattern: ObjectIdentifier(obj)))
}
let id = hashString(obj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With