Mastering ObjectIdentifier in Swift
Ensuring Uniqueness of Class Instances
3 min readJul 19, 2023
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) //…