With PR #14913, the stdlib has switched to a randomly seeded, high-quality hash function for all hashing. (The function is currently SipHash-1-3, but this is an implementation detail that is subject to change.)
"Random seeding" means that hashValue
properties will return different values on each execution of a Swift program. This is an important tool for improving the reliability of the Standard Library's hashing collections, Set
and Dictionary
. In particular, random seeding enables better protection against (accidental or deliberate) hash-flooding attacks.
This change fulfills a long-standing prophecy in Hashable
's documentation:
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.
All Hashable
types in the standard library (including primitive types like Bool
and Int
) now generate randomized hash values:
$ swift
1> 10.hashValue
$R0: Int = 3189672894122490707
2> 20.hashValue
$R1: Int = -731278079191967151
3> true.hashValue
$R2: Int = 1698870856037189238
4>
$ swift
1> 10.hashValue
$R0: Int = -7576852868862274754
2> 20.hashValue
$R1: Int = 6522600449632548270
3> true.hashValue
$R2: Int = 2902202285030183828
4>
I expect hash randomization will have minimal/no impact on the vast majority of existing code. Please let us know by posting here if you have questions or concerns.
Synthesized Hashable
implementations are currently still using a lesser form of hashing; I'm preparing an update to change this in PR #15122. Once this gets done, the next step is to consider making the new hashing interface public -- we can discuss this in Combining hashes.