我有一本字典
var observers: [ObservingType: [MessageObserverManager?]] = .init()作为我在这里使用的键枚举,但是由于某些原因它不起作用,字典不会用这些键创建任何对象。
enum ObservingType: Hashable {
case messages(codeId: Int, codeTwoId: Int)
case allMessages
case threadMessages(otherId: Int)
static func == (lhs: ObservingType, rhs: ObservingType) -> Bool {
return lhs.hashValue == rhs.hashValue
}
func hash(into hasher: inout Hasher) {
switch self {
case .messages(let codeId, let codeTwoId):
hasher.combine(codeId)
hasher.combine(codeTwoId)
hasher.combine(1000 / Int.random(in: 1...25))
case .allMessages:
hasher.combine(100000 / Int.random(in: 1...25))
case .threadMessages(let otherId):
hasher.combine(otherId)
hasher.combine(100000000 / Int.random(in: 1...25))
}
}你的建议是枚举有什么问题吗?
守卫observers.allMessages?.isEmpty ??false {observers.allMessages?.append(观察者)
return
}
observers[.allMessages] = [observer]这是我用来加值的代码,问题是我没有创建那些数组,所以原因不在枚举中,对不起,谢谢你的帮助!
发布于 2019-06-15 01:35:52
您的==实现不正确。不要比较哈希值。比较实际值。请记住,允许两个不相等的值具有相同的散列值。
您的hash实现不应该使用随机数。删除这些行。给定值的哈希值需要稳定(至少在应用程序的一次执行期间)。你不能在字典中查找那些不断变化的键的哈希值。
在这种情况下,最简单的解决方案是让编译器生成==和hash(into:)。那么你的代码就变成了:
enum ObservingType: Hashable {
case messages(codeId: Int, codeTwoId: Int)
case allMessages
case threadMessages(otherId: Int)
}这要简单得多,您现在可以将enum用作字典的键。
https://stackoverflow.com/questions/56602812
复制相似问题