Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the class instance ID in Swift?

Tags:

swift

In Objective-C, I would use the following code to identify an instance of a class and the function being called in the console.

NSLog(@"[DMLOG - %@] %@", NSStringFromSelector(_cmd), self);

This would return something like the console out below, where I would get an instance ID to track different instances of an object.

[DMLOG - prepForInput] <GridBase: 0x7fb71860a190>

How can I get both the instance ID and the function being called within Swift? I've tried the following to get the ID in Swift but it only provides the class name and no instance ID value? Any suggestions would be appreciated.

print("[DBG] Init: \(self)")
like image 262
XBXSlagHeap Avatar asked Dec 18 '22 00:12

XBXSlagHeap


1 Answers

To get current function name use #function literal.

As for instance ID, looks like you have two options:

  1. Inherit from NSObject (UIKit classes inherit it anyways) so that class instances would have instance IDs:

    class MyClass: NSObject {
      override init() {
        super.init()
        print("[DBG: \(#function)]: \(self)")
      }
    }
    
  2. If your class does not inherit from NSObject you can still identify your instances by memory address:

    class Jumbo {
      init() {
        print("[DBG: \(#function)]: \(Unmanaged.passUnretained(self).toOpaque())")
      }
    }
    
like image 97
Dan Karbayev Avatar answered Mar 30 '23 19:03

Dan Karbayev