swifthashtable

Swift, how to implement Hashable protocol based on object reference?


I've started to learn swift after Java. In Java I can use any object as a key for HashSet, cause it has default hashCode and equals based on object identifier. How to achieve the same behaviour in Swift?


Solution

  • If you are working with classes and not structs, you can use the ObjectIdentifier struct. Note that you also have to define == for your class in order to conform to Equatable (Hashable requires it). It would look something like this:

    class MyClass: Hashable { 
    
        static func == (lhs: MyClass, rhs: MyClass) -> Bool {
            ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
        }
    
        func hash(into hasher: inout Hasher) {
            hasher.combine(ObjectIdentifier(self))
        }
    
    }