Mastering ObjectIdentifier in Swift

Ensuring Uniqueness of Class Instances

Steven Curtis
3 min readJul 19


Photo by Jessica Ruscello on Unsplash

Before we start

Difficulty: Beginner | Easy | Normal | Challenging

Keywords and Terminology:

ObjectIdentifier: A unique identifier for a class instance or metatype


  • None


In Swift, class instances and metatypes have unique identities (because if we make a copy, we copy a reference to a unique instance).


You might create a simple Class type that represents a person, something (for simplicity's sake) that looks like the following:

class Person: Equatable {
static func == (lhs: Person, rhs: Person) -> Bool { ==

var name: String
init(_ name: String) { = name
let alisha = Person("Alisha")

Now we can create an identifier

let personIdentifier = ObjectIdentifier(alisha)

if we print (in this case) personIdentifier, we get a rather lovely address (and of course this is likely to differ on your machine):

print (personIdentifier) // ObjectIdentifier(0x0000600003fdb060

now since ObjectIdentifier conforms to both Equatable and Hashable if you compare two instances of alisha they will be true, but if you compare two instances of person that happen to have the same name (perhaps “Alisha”) they will only be equal if they are the SAME instance.

Equality matters

In Swift we have the equality operator === and this is essentially a wrapper for ObjectIdentifier.

Also, since ObjectIdentifier conforms to Hashable, this can be used in conjunction with Swift’s dictionaries.

var objectDictionary = [ObjectIdentifier: String]()
let metaObject = ObjectIdentifier(Person.self)
objectDictionary[metaObject] = "Test"

for object in objectDictionary {
print (object) // (key: ObjectIdentifier(0x000000010bd610b8), value: "Test")