make struct Hashable?

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)

  • 你应该只说“hasher.combine(dbName)”,因为“String”已经继承自“Hashable”。另外,您需要实现 == 运算符,并且“用于散列的组件必须与您类型的 == 运算符实现中比较的组件相同”,定义在[此处](https://developer.apple.com/文档/swift/hashable/2995575-hash)。 (4认同)