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

Dmitri Gribenko gribozavr at gmail.com
Fri Sep 2 18:02:28 CDT 2016

On Sat, Sep 3, 2016 at 1:31 AM, Zhao Xin via swift-users
<swift-users at swift.org> wrote:
> func ==(lhs: Apple, rhs: Apple) -> Bool {
>     return lhs.name == rhs.name && lhs.shape == rhs.shape
> }
> func ==(lhs: Banana, rhs: Banana) -> Bool {
>     return lhs.name == rhs.name && lhs.shape == rhs.shape
> }

There is no reason to compare the shape, it is a constant in each of
these types.  (So I am not sure what your point is.)

> My question is, apple equals banana, but their hashValues (in their own
> types)  don't. What's wrong here? Is that means we shouldn't override
> hashValue in subclass in Swift?

This means you should not override hashValue in this particular way.
If two values are equal, their hash values should be equal.  As long
as your override implementation guarantees this, you can override

You should also understand that the ==(Apple, Apple) and ==(Banana,
Banana) are not overrides for ==(Fruit, Fruit), and they would not be
called through dynamic dispatch when you have, for example, two apples
typed as fruits.


(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/

More information about the swift-users mailing list