Sobes.tech
Junior — Middle

Why is it important to define object equality in methods that are required to be implemented in the Hashable protocol?

sobes.tech AI

Answer from AI

In the Hashable protocol, defining object equality (via the == method) is critical because the object's hash value is used for fast lookup in collections such as sets or dictionaries.

If two objects are considered equal (by ==), their hash values must match. This ensures the correct operation of hash tables: objects with the same hash and equality are considered the same element.

Without a proper equality definition, errors can occur, such as duplicates in a Set or inability to find an element in a Dictionary, even if it exists.

Example:

struct User: Hashable {
    let id: Int
    let name: String

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

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

Here, equality is defined by id, and the hash is built on the same field, which guarantees correctness.