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 returnstrueif two objects are considered equal. -
Hashable extends
Equatableand adds the ability to obtain a hash value of the object through thehash(into:)property. This is necessary for using the object in collections with fast access, such asSetor as a key inDictionary.
Main differences:
-
Purpose:
Equatable— equality check.Hashable— obtaining a hash code for quick lookup.
-
Requirements:
Hashablerequires implementinghash(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.