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

前端 未结 5 1077
野趣味
野趣味 2020-12-29 04:16

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 objec

5条回答
  •  Happy的楠姐
    2020-12-29 04:49

    Another option is to implement an extension to Hashable and Equatable protocols for AnyObject. It seems to achieve a similar effect as the one you mentioned in Java.

    It adds a default behavior to all classes within your project and is not necessary the better option compared to adding such behavior to only a designated class. So, I am just mentioning it for the sake of completeness:

    class HashableClass: Hashable {
    
    
    }
    
    extension Hashable where Self: AnyObject{
    
      func hash(into hasher: inout Hasher) {
    
         hasher.combine(ObjectIdentifier(self))
       }
    }
    
    
    extension Equatable where Self: AnyObject{
    
       static func ==(lhs: Self, rhs: Self) -> Bool {
          return lhs === rhs
       }
    }
    

    Now, if you you would like to implement specific logic for your class, you could still do that, like this:

    class HashableClass { //deleted the Hashable conformance
    
    
    }
    extension HashableClass : Hashable{
    
       func hash(into hasher: inout Hasher) {
    
          //your custom hashing logic
       }
    }
    

    To avoid adding default behavior to AnyObject, another protocol can be declared and extension relevant only to this new protocol can be added:

    protocol HashableClass : AnyObject{
    
    }
    
    class SomeClass: Hashable, HashableClass {
    
    
     }
    
     extension Hashable where Self: HashableClass{
    
       func hash(into hasher: inout Hasher) {
    
          hasher.combine(ObjectIdentifier(self))
       }
     }
    
    
    extension Equatable where Self: HashableClass{
    
       static func ==(lhs: Self, rhs: Self) -> Bool {
         return lhs === rhs
       }
    }
    

提交回复
热议问题