Member-only story

Mastering ObjectIdentifier in Swift

Ensuring Uniqueness of Class Instances

--

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

Prerequisites:

  • None

Why

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

Usage

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 {
lhs.name == rhs.name
}

var name: String
init(_ name: String) {
self.name = 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")
}

--

--

Responses (1)