Junior — Middle
What properties must an object implementing the Hashable protocol have to be used in hash tables?
sobes.tech AI
Answer from AI
An object that conforms to the Hashable protocol in iOS (Swift) must have the following properties:
-
Conformance to the Hashable protocol — the object must implement the
hash(into:)method, which adds all significant properties for hashing into the hash function. -
Equatability (Equatable) — objects considered equal (via the
==operator) must have the same hash.
This is necessary so that the object can be used in hash tables (for example, in Set or as a key in Dictionary), where the hash determines the position of the element, and equality determines uniqueness.
Example implementation:
struct User: Hashable {
var id: Int
var name: String
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id
}
}
Here, id is a unique identifier used to determine the hash and equality.