Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a unique String for a given AnyObject?

Tags:

swift

In Objective-C, this was as simple as:

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

How can I do this in Swift?

like image 514
aleclarson Avatar asked Jun 12 '14 15:06

aleclarson


3 Answers

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)))
like image 183
aleclarson Avatar answered Oct 17 '22 23:10

aleclarson


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)"
}
like image 26
newacct Avatar answered Oct 17 '22 23:10

newacct


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)
like image 3
worriorbg Avatar answered Oct 18 '22 00:10

worriorbg