Safe Hashable in Swift
This is the way to create safe
Hashable based on @rayfix’s talk.
In this case, there is no problem here because a hashValue is unique.
BadPoint(x: 2.0, y: 3.0) and
BadPoint(x: 3.0, y: 2.0) are not same object, but they have a same hashValue. This is a problem.
As @rayfix mentioned in his talk, heap allocations are expensive compared to previous way! And looks a little bit ugly:(
This is what he did to avoid a collision.
This way uses
FNV-1a hash as a hash algorithm.
The FNV-1a hash differs from the FNV-1 hash by only the order in which the multiply and XOR is performed
hash = FNV_offset_basis for each byte_of_data to be hashed hash = hash XOR byte_of_data hash = hash × FNV_prime return hash
The another interesting way to solve these problems is from Sourcery’s AutoHashable. But Sourcery create
AutoHashable automatically. Awesome!!