[swift-users] Can we `override var hashValue`?

Lou Zell lzell11 at gmail.com
Tue Sep 6 16:55:19 CDT 2016


>
> My question is, apple equals banana, but their hashValues (in their own
> types)  don't. What's wrong here?

​
Hi Zhao.  In addition to what Jordan and Dmitri have said, I think part of
the confusion is that you are assuming hash values are implicitly used in
an equality check.  They are not.  They are used when your instances are
added to certain types of collections.

In your first example, where you print out the hash values but then compare
lhs.name to rhs.name, the names of the two fruits are both "common fruit",
and the equality test returns true.  Hash never comes into play.  You can
test for yourself when the hash gets used:

import Foundation
class Foo: NSObject {
    override var hash: Int {
        print("Computing hash value!")
        return 1
    }
}
var f1 = Foo()
var f2 = Foo()
f1 == f2  // Doesn't print anything!
var aSet = Set<Foo>()
aSet.insert(f1)  // Prints "Computing has value!"

Lou
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160906/c26fd364/attachment.html>


More information about the swift-users mailing list