Get a unique string for this AnyObject?

In Objective-C, it was as simple as:

[NSString stringWithFormat:@"%p", objRef]

How to do it in Swift?

+9
source share
4 answers
 func hashString (obj: AnyObject) -> String { return String(ObjectIdentifier(obj).uintValue) } let id = hashString(obj) 

Swift 3.0

 return String(UInt(ObjectIdentifier(obj)) 
+25
source

How about direct translation:

 func pointerToString(objRef: NSObject) -> String { return NSString(format: "%p", objRef) } 

A more native path (in decimal rather than hexadecimal):

 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 are building correctly now, so you can just do

 func pointerToString(objRef: AnyObject) -> String { let ptr: COpaquePointer = Unmanaged<AnyObject>.passUnretained(objRef).toOpaque() return "\(ptr)" } 
+7
source

what you could do to resolve the error is pretty much this:

  func pointerToString<T> (ptr: CMutablePointer<T>) -> String { // ... } 

but printing the actual pointer in Swift is not possible.

0
source

You can not. A private line in Swift is an object with a different and opaque memory layout than the contents of any memory at the CMutablePointer address. Therefore, you cannot appoint each other. An alternative is to assign / copy NSString, which was initialized by the contents of the memory at the address of the pointer.

-1
source

Source: https://habr.com/ru/post/1210134/


All Articles