How to conform to Hashable for class in Swift

Issue #606

Use ObjectIdentifier

A unique identifier for a class instance or metatype.

final class Worker: Hashable {
    static func == (lhs: Worker, rhs: Worker) -> Bool {
        return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(ObjectIdentifier(self))
    }
}
Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation