Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4: Inbuilt String.hashValue generates same result for different strings

Tags:

swift

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?
  • If we trim both strings by a single character, the hashValues are different.
  • If we append different characters, the hashValues are different.
  • If we append identical characters, the hashValues are the same.

Would love to understand what's going on here...

Thanks

like image 685
Nash Avatar asked Jan 03 '23 13:01

Nash


2 Answers

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 and b of the same type, if a == b, then a.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

like image 176
nayem Avatar answered Jan 05 '23 03:01

nayem


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,

like image 32
Wendra Avatar answered Jan 05 '23 02:01

Wendra