Reputation: 266
While generating hash values using Swift's built in string hashValue, we found a case where two different strings generate the same hash value... but the cause of the collision is very perplexing..
Take these two strings:
var str1 = """
00000000000000
00000000000000
00000000000000
00000000000000
00000000000000
00000000100000
00000000000000
00000000000
""" //Contains a single 1 character
var str2 = """
00000000000000
00000000000000
00000000000000
00000000000000
00000000000000
00000000000000
00000000000000
00000000000
""" //Contains only zeroes
str1 == str2 // false
str1.hashValue == str2.hashValue // true ..WAT?
Would love to understand what's going on here...
Thanks
Upvotes: 4
Views: 5816
Reputation: 7585
Take a look at official documentation from Apple on Hashable protocol. It says:
A hash value, provided by a type’s hashValue property, is an integer that is the same for any two instances that compare equally. That is, for two instances
a
andb
of the same type, ifa == b
, thena.hashValue == b.hashValue
. The reverse is not true: Two instances with equal hash values are not necessarily equal to each other.
You can also get more by reading this post
Upvotes: 8
Reputation: 517
Don’t ever assume that two items with the same hash value are equal. This happens because you XOR the individual hash values but XOR’ing a value with itself gives zero (A ^ A = 0).
Maybe this article would give you the answer
https://useyourloaf.com/blog/swift-hashable/
Cheers,
Upvotes: 2