使结构可哈希? [英] Make struct Hashable?
问题描述
我正在尝试创建 [petInfo : UIImage]()
类型的字典,但我收到错误 Type 'petInfo' 不符合协议 'Hashable'代码>.我的 petInfo 结构是这样的:
I'm trying to create a dictionary of the sort [petInfo : UIImage]()
but I'm getting the error Type 'petInfo' does not conform to protocol 'Hashable'
. My petInfo struct is this:
struct petInfo {
var petName: String
var dbName: String
}
所以我想以某种方式使它可散列,但它的任何组件都不是整数,这正是 var hashValue: Int
所要求的.如果它的所有字段都不是整数,我如何使其符合协议?如果我知道 dbName
对于此结构的所有出现都是唯一的,我可以使用它吗?
So I want to somehow make it hashable but none of its components are an integer which is what the var hashValue: Int
requires. How can I make it conform to the protocol if none of its fields are integers? Can I use the dbName
if I know it's going to be unique for all occurrences of this struct?
推荐答案
只需从 hashValue
函数返回 dbName.hashValue
.仅供参考 - 哈希值不需要是唯一的.要求是两个相等的对象也必须具有相同的哈希值.
Simply return dbName.hashValue
from your hashValue
function. FYI - the hash value does not need to be unique. The requirement is that two objects that equate equal must also have the same hash value.
struct PetInfo: Hashable {
var petName: String
var dbName: String
var hashValue: Int {
return dbName.hashValue
}
static func == (lhs: PetInfo, rhs: PetInfo) -> Bool {
return lhs.dbName == rhs.dbName && lhs.petName == rhs.petName
}
}
这篇关于使结构可哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!