Mar*_*ode 31 dictionary hashable swift swift3
我正在尝试创建一个类型的字典,[petInfo : UIImage]()但我收到了错误Type 'petInfo' does not conform to protocol 'Hashable'.我的petInfo结构是这样的:
struct petInfo {
var petName: String
var dbName: String
}
Run Code Online (Sandbox Code Playgroud)
所以我想以某种方式使它可以清除,但它的组件都不是一个整数,这是var hashValue: Int需要的.如果它的字段都不是整数,我怎样才能使它符合协议?dbName如果我知道它对于所有这个结构的出现都是唯一的,我可以使用吗?
rma*_*ddy 48
只需dbName.hashValue从您的hashValue功能返回.仅供参考 - 哈希值不需要是唯一的.要求是两个等于等于的对象也必须具有相同的散列值.
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
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*isH 25
截至 Swift 5var hashValue:Int已被弃用func hash(into hasher: inout Hasher)(在 Swift 4.2 中引入),因此更新答案@rmaddy 使用:
func hash(into hasher: inout Hasher) {
hasher.combine(dbName)
}
Run Code Online (Sandbox Code Playgroud)