Hash different for the same object, Swift, Hashable

依然范特西╮ 提交于 2020-01-30 03:21:15

问题


Inside of the Hashable we can see:

/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.

Why it is so? Getting different hash for the same object on every run confuses me because in the university I studied that hash function return same value for same object. What algorithm is Apple using for hashing?

E.G. (this will print the different value on every run)

struct HashTesting: Hashable {
    var a = 10
    var b = 20
    var str = "str"
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let obj = HashTesting(a: 10, b: 10, str: "str")
        print("\(obj.hashValue)")
    }
}

回答1:


Hash randomization was enforced in Swift 4.2, with the implementation of SE 0206 Hashable Enhancements. From the proposal:

However, Hasher may generate entirely different hash values in other executions, even if it is fed the exact same byte sequence. This randomization is a critical feature, as it makes it much harder for potential attackers to predict hash values. Hashable has always been documented to explicitly allow such nondeterminism.

In addition, it allows the actual implementation to be changed (e.g. improved) in the Swift standard library, without breaking compatibility.

For debugging purposes the hash randomization can be disabled by defining the SWIFT_DETERMINISTIC_HASHING environment variable with a value of 1.

The implementation of the Swift standard hasher can be found in the open source repository:

  • https://github.com/apple/swift/blob/master/stdlib/public/core/Hasher.swift
  • https://github.com/apple/swift/blob/master/stdlib/public/core/SipHash.swift

It is based on SipHash.



来源:https://stackoverflow.com/questions/57817954/hash-different-for-the-same-object-swift-hashable

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