Sobes.tech
Junior — Middle

How does Swift determine the difference between two objects when a hash collision occurs?

sobes.tech AI

Answer from AI

In Swift, the isEqual(_:) method is used for comparing objects and resolving hash collisions. When two objects have the same hash (collision), the system additionally calls this method to verify if the objects are truly equal.

Process:

  1. The hash of the object is computed via hash(into:).
  2. If two objects have the same hash, isEqual(_:) is called for an exact comparison.
  3. If isEqual(_:) returns true, the objects are considered equal; otherwise, they are different.

This allows correct operation with collections such as Set or dictionary keys, even in case of hash collisions.

Example implementation:

class Person: Hashable {
    let id: Int
    let name: String

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

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

Here, if two Person objects have the same hash (for example, the same id), the == operator will be called for final comparison.