Sobes.tech
Junior — Middle

What is the relationship between Hashable and Equatable protocols in Swift?

sobes.tech AI

Answer from AI

In Swift, the protocols Equatable and Hashable are closely related, since Hashable inherits from Equatable.

  • Equatable requires the implementation of the equality operator == to compare two instances for equality.
  • Hashable extends Equatable and requires the implementation of the hashValue property (or the hash(into:) method), which returns the hash code of the object.

The connection is that to compute the hash code of an object, you need to be able to compare objects for equality to work correctly with hash-based collections (such as Set or Dictionary).

Example:

struct Person: Hashable {
    var id: Int
    var name: String

    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

Here, Person conforms to both Equatable and Hashable, allowing it to be used in hash tables.

What is the relationship between Hashable and… - sobes.tech