swift – 符合Hashable协议?
发布时间:2020-12-14 05:23:40 所属栏目:百科 来源:网络整理
导读:我正在尝试使用键创建一个字典作为我创建的结构,并将值作为Ints数组.但是,我一直收到错误:类型’dateStruct’不符合协议’Hashable’.我很确定我已经实现了必要的方法但由于某种原因它仍然不起作用.这是我的结构与实现的协议: struct dateStruct { var yea
我正在尝试使用键创建一个字典作为我创建的结构,并将值作为Ints数组.但是,我一直收到错误:类型’dateStruct’不符合协议’Hashable’.我很确定我已经实现了必要的方法但由于某种原因它仍然不起作用.这是我的结构与实现的协议:
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 } } } } } 任何人都可以向我解释为什么我仍然会收到错误?
你错过了声明:
struct dateStruct: Hashable { BTW – 结构和类名称应以大写字母开头. 你的==函数是错误的.您应该比较这三个属性. static func == (lhs: dateStruct,rhs: dateStruct) -> Bool { return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day } 两个不同的值可能具有相同的哈希值. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |