In Objective-C, this was as simple as:
[NSString stringWithFormat:@"%p", objRef]
How can I do this in Swift?
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)
what you could do to resolve the error is pretty much this:
func pointerToString<T> (ptr: CMutablePointer<T>) -> String {
// ...
}
but printing the actual pointer is not really possible in Swift.
You can't. A native String in Swift is an object with a different and opaque memory layout than the contents of whatever memory is located at the CMutablePointer address. So you can't assign one to another. An alternative is to assign/copy an NSString that has been initialized with the contents of the memory at the pointer address.