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)")
}
}
Hash randomization was enforced in Swift 4.2, with the implementation of SE 0206 Hashable Enhancements. From the proposal:
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.