使结构化Hashable? [英] Make struct Hashable?
问题描述
我正在尝试创建排序的字典 [petInfo:UIImage]()
但是我收到错误类型'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
。 FYI - 哈希值不一定是唯一的。要求是等于等于的两个对象也必须具有相同的哈希值。
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
}
}
这篇关于使结构化Hashable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!