我正在延长一个struct
符合Hashable
。我将使用DJB2哈希组合器来完成此操作。
为了使编写其他东西的哈希函数变得容易,我想扩展Hashable
协议,以便我的哈希函数可以这样写:
extension MyStruct: Hashable {
public var hashValue: Int {
return property1.combineHash(with: property2).combineHash(with: property3)
}
}
但是当我尝试将扩展名写入Hashable
实现 `combineHash(with:),如下所示:
extension Hashable {
func combineHash(with hashableOther:Hashable) -> Int {
let ownHash = self.hashValue
let otherHash = hashableOther.hashValue
return (ownHash << 5) &+ ownHash &+ otherHash
}
}
...然后我得到这个编译错误:
/Users/benjohn/Code/Nice/nice/nice/CombineHash.swift:12:43:协议“Hashable”只能用作通用约束,因为它具有 Self 或关联的类型要求
这是 Swift 不允许我做的事情,还是我只是做错了并收到无用的错误消息?
AsideJAL 的评论链接至快速哈希函数的代码审查这也是由马丁写的,他在下面提供了公认的答案!他在那次讨论中提到了一种不同的哈希组合器,该组合器基于 c++ boost 库中的一个。讨论确实值得一读。替代组合器的冲突较少(在测试的数据上)。
使用方法hash(into:)
来自苹果开发者文档:
https://developer.apple.com/documentation/swift/hashable
struct GridPoint {
var x: Int
var y: Int
}
extension GridPoint: Hashable {
static func == (lhs: GridPoint, rhs: GridPoint) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)