我正在尝试创建一个字典,将key作为我创建的结构,值作为Int数组。但是,我一直收到错误:
类型“”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
}
}
}
}
}有谁能给我解释一下为什么我仍然收到这个错误?
发布于 2017-02-22 12:53:50
你遗漏了声明:
struct DateStruct: Hashable {还有你的
函数错误。您应该比较这三个属性。
static func == (lhs: DateStruct, rhs: DateStruct) -> Bool {
return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day
}两个不同的值有可能具有相同的散列值。
发布于 2019-03-12 17:50:17
如果不想使用hashValue,可以将值的散列与
方法。
有关详细信息,请参阅答案:
https://stackoverflow.com/a/55118328/1261547
发布于 2021-03-01 19:13:23
对于简单结构,其中它的所有属性都已
(即
,... ),我们可以遵循
只需声明它(请参见
https://developer.apple.com/documentation/swift/hashable
)
所以不需要实现
( btw已弃用)或
(因为
符合
)。
由于我们正在实现
运算符,那么符合
,所以我们可以排序(即
)。
所以我会这样做:
struct DateStruct: Comparable & Hashable {
let year: Int
let month: Int
let day: Int
static func < (lhs: DateStruct, rhs: DateStruct) -> Bool {
if lhs.year != rhs.year {
return lhs.year < rhs.year
} else if lhs.month != rhs.month {
return lhs.month < rhs.month
} else {
return lhs.day < rhs.day
}
}
}https://stackoverflow.com/questions/42382960
复制相似问题