gpt4 book ai didi

swift - 我应该如何计算哈希值?

转载 作者:行者123 更新时间:2023-11-30 12:05:55 30 4
gpt4 key购买 nike

我看到了几个 Hashable 变量 hashValue 的实现示例,例如:

extension Country: Hashable {
var hashValue: Int {
return name.hashValue ^ capital.hashValue ^ visited.hashValue
}
}


var hashValue: Int {
return self.scalarArray.reduce(5381) {
($0 << 5) &+ $0 &+ Int($1)
}
}


var hashValue : Int {
get {
return String(self.scalarArray.map { UnicodeScalar($0) }).hashValue
}
}

等等。在某些情况下,会使用ORXORBITWISE 运算符。在其他情况下,其他算法、映射或过滤函数等。

现在我有点困惑。计算良好的 hashValue 的经验法则是什么?

在最简单的有两个字符串变量的情况下,我应该用 OR 运算符将这两个变量组合起来吗?

最佳答案

从 Swift 4.2 开始,您可以使用 Hasher

Swift 4.2 implements hashing based on the SipHash family of pseudorandom functions, specifically SipHash-1-3 and SipHash-2-4, with 1 or 2 rounds of hashing per message block and 3 or 4 rounds of finalization, respectively.

Now if you want to customize how your type implements Hashable, you can override the hash(into:) method instead of hashValue. The hash(into:) method passes a Hasher object by reference, which you call combine(_:) on to add the essential state information of your type.

// Swift >= 4.2
struct Color: Hashable {
let red: UInt8
let green: UInt8
let blue: UInt8

// Synthesized by compiler
func hash(into hasher: inout Hasher) {
hasher.combine(self.red)
hasher.combine(self.green)
hasher.combine(self.blue)
}

// Default implementation from protocol extension
var hashValue: Int {
var hasher = Hasher()
self.hash(into: &hasher)
return hasher.finalize()
}
}

关于swift - 我应该如何计算哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46686046/

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