Sobes.tech
Junior

What is Hashable in Swift?

sobes.tech AI

Answer from AI

The Hashable protocol allows objects to be used in hash-based collections such as Set and Dictionary. The conforming type must provide a hashValue that generates a hash for the object.

Main points:

  • Types conforming to Hashable generate an integer value representing their hash.
  • If two objects are equal (==), their hash values must be the same.
  • If two objects have the same hash value, they are not necessarily equal.
  • Swift automatically synthesizes Hashable conformance for structs and enums if all their members conform to Hashable.
  • For classes or custom structs with non-Hashable members, hash(into:) must be implemented manually.

Example of manual implementation:

struct MyStruct {
    let id: Int
    let name: String
}

extension MyStruct: Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
        hasher.combine(name)
    }
}
What is Hashable in Swift? — iOS - sobes.tech