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

前端 未结 5 1091
野趣味
野趣味 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条回答
  •  猫巷女王i
    2020-12-29 04:38

    Here's another protocol-only (i.e. no base-class) solution but it simplifies how you use it while still making it opt-in. You use constrained extensions to adhere to both the Hashable and Equatable protocols.

    Several implementations will use a class extension to adopt protocol conformance, like this...

    extension SomeClass : Hashable {
    
        func hash(into hasher: inout Hasher) {
            hasher.combine(ObjectIdentifier(self))
        }
    }
    

    But instead, we reverse it by extending the protocol itself, then using a constraint of AnyClass which makes this implementation work for all classes that simply specify conformance to the protocol, no class-specific implementation needed...

    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
        }
    }
    

    With the above both in place, we can now do this...

    class Foo : Hashable {} // Defining with the class definition
    var fooToStringLookup:[Foo:String] = [:]
    
    class Laa {}
    extension Laa : Hashable {} // Adding to an existing class via an extension
    var laaToIntLookup:[Laa:Int] = [:]
    

    Of course Hashable also gives you Equatable implicitly, so these all now work too...

    let a = Foo()
    let b = a
    let msg = (a == b)
        ? "They match! :)"
        : "They don't match. :(" 
    print(msg)
    

    Note: This will not interfere with classes that implement Hashable directly as a class-specific definition is more explicit, thus it takes precedence and these can peacefully coexist.

    Going a step further, and speaking only about Equatable, if you want to make all object types implement Equatable and adhere to reference-semantics implicitly--something I personally wonder why it doesn't do this by default (and which you can still override per-type if needed)--you can use generics with a globally-defined equality operator, setting the constraint to AnyObject

    func == (lhs: T, rhs: T) -> Bool {
        return lhs === rhs
    }
    
    func != (lhs: T, rhs: T) -> Bool {
        return !(lhs == rhs)
    }
    

    Note: For completeness, you should also explicitly provide the != operator as unlike when defining the = operator in an extension, the compiler will not synthesize it for you.

    With that, now you can do this...

    class Laa {} // Note no protocols or anything else specified. Equality 'just works'
    
    let a = Laa()
    let b = a
    var msg = (a == b)
        ? "They match! :)"
        : "They don't match. :(" 
    print(msg)
    
    // Prints 'They match! :)'
    
    let c = Laa()
    var msg = (a == c)
        ? "They don't match! :)"
        : "They match. :(" 
    print(msg)
    
    // Prints 'They don't match! :)'
    

    As mentioned above, you can still use type-specific versions of equality as well. This is because they take precedence over the AnyObject version as they are more specific, and thus can peacefully coexist with the default reference-equality provided above.

    Here's an example that assumes the above is in place, but still defines an explicit version of equality for Hee, based solely on id.

    class Hee {
        init(_ id:String){
            self.id = id
        }
        let id:String
    }
    
    // Override implicit object equality and base it on ID instead of reference
    extension Hee : Equatable {
    
        static func == (lhs:Hee, rhs:Hee) -> Bool {
            return lhs.id == rhs.id
        }
    }
    

    Caution: If the object you are overriding equality on also implements Hashable, you must ensure the corresponding hash values are also equal as by definition, objects that are equal should produce the same hash value.

    That said, if you have the Hashable extension constrained to AnyObject from the top of this post, and simply tag your class with Hashable you will get the default implementation which is based on the object's identity so it will not match for different class instances that share the same ID (and thus are considered equal), so you must explicitly make sure to implement the hash function as well. The compiler will not catch this for you.

    Again, you only have to do this if you are overriding equality and your class implements Hashable. If so, here's how to do it...

    Implement hashable on Hee to follow the equality/hashable relationship:

    extension Hee : Hashable {
    
        func hash(into hasher: inout Hasher) {
            hasher.combine(id) // Easiest to simply use ID here since that's what Equatable above is based on
        }
    }
    

    And finally, here's how you use it...

    let hee1 = Hee("A")
    let hee2 = Hee("A")
    let msg2 = (hee1 == hee2)
        ? "They match! :)"
        : "They don't match. :("
    print(msg2)
    
    // Prints 'They match! :)'
    
    let set = Set()
    set.append(hee1)
    set.append(hee2)
    print("Set Count: \(set.count)")
    
    // Prints 'Set Count: 1'
    

提交回复
热议问题