Hash different for the same object, Swift, Hashabl

2020-03-31 07:25发布

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

标签: ios swift hash
1条回答
姐就是有狂的资本
2楼-- · 2020-03-31 07:55

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:

It is based on SipHash.

查看更多
登录 后发表回答