Make struct Hashable?

被刻印的时光 ゝ 提交于 2019-11-28 21:08:25

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

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