Search code examples
swiftprotocolshashable

What is the use of hashable protocol in swift4?


please explain the use of hashable protocol with implementation in swift. Apple defines hashable as “a type that provides an integer a hash value.” Okay, but what’s a hash value?


Solution

  • To make an object conform to Hashable we need to provide a hashValue property that will return a unique, consistent number for each instance. The Hashable protocol inherits from Equatable, so you may also need to implement an == function.

    Note: If two objects compare as equal using == they should also generate the same hash value, but the reverse isn’t true – hash collisions can happen.

    Before Swift 4.1, conforming to Hashable was complex because you needed to calculate a hashValue property by hand. In Swift 4.1 this improved so that hashValue could be synthesized on your behalf if all the properties conform to Hashable . Swift 4.2 introduces a new Hasher struct that provides a randomly seeded, universal hash function to make all our lives easier. Refer for more