Conforming to Hashable protocol?

MarksCode picture MarksCode · Feb 22, 2017 · Viewed 32.2k times · Source

I'm trying to make a dictionary with the key as a struct I've created and the value as an array of Ints. However, I keep getting the error:

Type 'DateStruct' does not conform to protocol 'Hashable'

I'm pretty sure I've implemented the necessary methods but for some reason it still doesn't work.

Here's my struct with the implemented protocols:

struct DateStruct {
    var year: Int
    var month: Int
    var day: Int

    var hashValue: Int {
        return (year+month+day).hashValue
    }

    static func == (lhs: DateStruct, rhs: DateStruct) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }

    static func < (lhs: DateStruct, rhs: DateStruct) -> Bool {
        if (lhs.year < rhs.year) {
            return true
        } else if (lhs.year > rhs.year) {
            return false
        } else {
            if (lhs.month < rhs.month) {
                return true
            } else if (lhs.month > rhs.month) {
                return false
            } else {
                if (lhs.day < rhs.day) {
                    return true
                } else {
                    return false
                }
            }
        }
    }
}

Can anybody please explain to me why I'm still getting the error?

Answer

rmaddy picture rmaddy · Feb 22, 2017

You're missing the declaration:

struct DateStruct: Hashable {

And your == function is wrong. You should compare the three properties.

static func == (lhs: DateStruct, rhs: DateStruct) -> Bool {
    return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day
}

It's possible for two different values to have the same hash value.