XBXSlagHeap
XBXSlagHeap

Reputation: 174

How do I get the class instance ID in 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)")

Upvotes: 4

Views: 6658

Answers (2)

Dan Karbayev
Dan Karbayev

Reputation: 2920

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())")
      }
    }
    

Upvotes: 14

Shawn
Shawn

Reputation: 416

I just ran a quick test using the following:

print("\(self) \(#function) - Count \(count)")

I got the following result:

<XXXXXXX.FeedViewController: 0x7fcebdf05d40> viewWillAppear - Count 3

I would give that a try and see if it helps.

Upvotes: 0

Related Questions