Make struct Hashable?

孤者浪人 提交于 2019-11-27 13:29:55

问题


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
}

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?


回答1:


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
    }
}



回答2:


As of Swift 5 var hashValue:Int has been deprecated in favour of func hash(into hasher: inout Hasher) (introduced in Swift 4.2), so to update the answer @rmaddy gave use:

func hash(into hasher: inout Hasher) {
    hasher.combine(dbName.hashValue)
}


来源:https://stackoverflow.com/questions/41972319/make-struct-hashable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!