iOS Dev Nugget 240 Print an Object's Unique Identifier


Need to run a code review on your codebase? Hire me

Sometimes, in Swift — especially for debugging — you will want to see if 2 objects references you are holding are actually referring to the same object. The ObjectIdentifier struct is useful for this.

var o1 = NSObject()
var o2 = o1
var o3 = NSObject()
print("o1's \(ObjectIdentifier(o1).debugDescription)")
print("o2's \(ObjectIdentifier(o2).debugDescription)")
print("o3's \(ObjectIdentifier(o3).debugDescription)")

You'll get something a unique identifier for each object instance like this and you can see that o1 and o2 refers to the same instance.

o1's ObjectIdentifier(0x0000608000001620)
o2's ObjectIdentifier(0x0000608000001620)
o3's ObjectIdentifier(0x0000610000001530)

Note that ObjectIdentifier doesn't work for value types like structs and enums.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues