gpt4 book ai didi

swift - 在 Swift 中实现哈希组合器

转载 作者:搜寻专家 更新时间:2023-10-31 08:17:42 26 4
gpt4 key购买 nike

我正在扩展一个符合Hashablestruct。我将使用 DJB2哈希组合器来完成这个。

为了方便为其他东西编写哈希函数,我想扩展Hashable协议(protocol),这样我的哈希函数就可以这样写:

extension MyStruct: Hashable {
public var hashValue: Int {
return property1.combineHash(with: property2).combineHash(with: property3)
}
}

但是当我尝试将扩展写入实现`combineHash(with:) 的Hashable 时,如下所示:

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: Protocol 'Hashable' can only be used as a generic constraint because it has Self or associated type requirements

这是 Swift 不允许我做的事情,还是我只是做错了并且收到了无用的错误消息?


旁白 来自 JAL 的评论链接到 a code review of a swift hash function这也是由 Martin 撰写的,他在下面提供了公认的答案!他在那次讨论中提到了一个不同的哈希组合器,它基于 c++ boost 库中的一个。讨论确实值得一读。替代组合器的碰撞较少(在测试的数据上)。

最佳答案

使用 Apple 开发者文档中的 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)
}

}

关于swift - 在 Swift 中实现哈希组合器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42627014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com