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

Zhao Xin owenzx at gmail.com
Fri Sep 2 17:31:41 CDT 2016


In Objective-C, it says

If two objects are equal, they must have the same hash value. This last
> point is particularly important if you define isEqual: in a subclass and
> intend to put instances of that subclass into a collection. Make sure you
> also define hash in your subclass.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/index.html#//apple_ref/occ/intfm/NSObject/isEqual:
>


​So the conclusion is that hash can be override.

However, in Swift, things go a little odd. Below code works in both Swift
2.2(Xcode 7.3.1) and Swift 3.0(Xcode 8 beta 6).

func ==(lhs: Fruit, rhs: Fruit) -> Bool {

    print(lhs.hashValue)

    print(rhs.hashValue)



    return lhs.name == rhs.name

}


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

}



class Fruit:Hashable {

    let name:String



    var hashValue: Int {

        return 0

    }



    init(_ name:String = "common fruit") {

        self.name = name

    }

}


enum FruitShape:Int {

    case small = 1000

    case medium = 2000

    case big = 3000

}


class Apple:Fruit {

    let shape:FruitShape = .medium



    override var hashValue: Int {

        return 5

    }

}


class Banana:Fruit {

    let shape:FruitShape = .big



    override var hashValue: Int {

        return 10

    }

}


let apple = Apple()

let banana = Banana()


print(apple == banana)

/*

 5

 10

 true
*/

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?

Zhaoxin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160903/13ad4c82/attachment.html>


More information about the swift-users mailing list