Sobes.tech
Junior — Middle

What are the differences between Hashable and Equatable protocols in terms of their purpose and operation?

sobes.tech AI

Answer from AI

The Equatable and Hashable protocols in Swift serve different purposes, although they are often used together.

  • Equatable defines the ability to compare objects for equality. To conform to this protocol, you need to implement the == function, which returns true if two objects are considered equal.

  • Hashable extends Equatable and adds the ability to obtain a hash value of the object through the hash(into:) property. This is necessary for using the object in collections with fast access, such as Set or as a key in Dictionary.

Main differences:

  1. Purpose:

    • Equatable — equality check.
    • Hashable — obtaining a hash code for quick lookup.
  2. Requirements:

    • Hashable requires implementing hash(into:) and implies that objects equal under == have the same hash.

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 is considered equal if the id matches, and the hash is built based on id. This allows Person to be used in a Set or as a key in a Dictionary.

If a type conforms only to Equatable, it cannot be used in collections that require hashing.

What are the differences between Hashable and… - sobes.tech