我一直在尝试在“结构”中声明一个静态字典。但是,我无法做到这一点。它给了我“Type 'BagItem' does not conform to protocol 'Hashable'”。
我的代码在这里:
struct StaticBag {
static var bag: Dictionary<BagItem, Array<BagItem>> = Dictionary<BagItem, Array<BagItem>>()
// static func AddMainItem(item: BagItem)
// {
// self.bag[item] = Array<BagItem>()
// }
}
代码中的'BagItem' 是我的另一个全局类。 声明此变量的正确和最佳方法是什么?
谢谢你的回答
最好的问候
最佳答案
正如它所说,问题是您的自定义 BagItem
类型不符合 Hashable
协议(protocol)。字典键需要是可哈希的,因为字典使用哈希值来快速查找条目。
BagItem
是什么样子的?是否有一个已经可散列的唯一属性?如果是这样,您可以通过添加 hashValue
属性并实现 ==
运算符来添加 Hashable
一致性:
class BagItem : Hashable {
var uniqueID: Int = 0
var hashValue: Int { return uniqueID.hashValue }
}
func ==(lhs: BagItem, rhs: BagItem) -> Bool {
return lhs.uniqueID == rhs.uniqueID
}
关于ios - swift 中的静态字典类型变量声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26078418/