符合Hashable协议?

Mar*_*ode 9 struct hashable swift swift3

我正在尝试使用键创建一个字典作为我创建的结构,并将值作为Ints数组.但是,我不断收到错误:__CODE__.我很确定我已经实现了必要的方法但由于某种原因它仍然不起作用.这是我的结构与实现的协议:

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
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我解释为什么我仍然会收到错误?

rma*_*ddy 22

你错过了声明:

struct DateStruct: Hashable {
Run Code Online (Sandbox Code Playgroud)

BTW - 结构和类名称应以大写字母开头.

而你的==功能是错误的.您应该比较这三个属性.

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

两个不同的值可能具有相同的哈希值.


Hat*_*tim 9

如果该类具有类型(另一个类)的字段,则该类应采用 Hashable。

例子

struct Project : Hashable {
    var activities: [Activity]?

}
Run Code Online (Sandbox Code Playgroud)

这里,Activity类也必须采用Hashable。


Ant*_*hko 7

顺便提一句

var hashValue: Int 
Run Code Online (Sandbox Code Playgroud)

已过时(除了在遗留的 NSObject 继承树中)。

    func hash(into hasher: inout Hasher)
    {
        hasher.combine(year);
        hasher.combine(month) 
    ...
Run Code Online (Sandbox Code Playgroud)

是新方法


Lil*_*ilo 6

如果您不想使用 hashValue,则可以将值的散列与该hash(into:)方法结合使用。

有关更多信息,请参阅答案:https : //stackoverflow.com/a/55118328/1261547