Junior — Middle
Can you explain how the Hashable protocol is implemented and what role it plays in managing object uniqueness in Swift?
sobes.tech AI
Answer from AI
The Hashable protocol in Swift is used to make objects hashable, meaning they have a unique hash code that allows them to be used in collections like Set or as keys in dictionaries.
To implement Hashable, you need to define the hash(into:) method, which combines the properties of the object into a hash function, and also conform to the Equatable protocol (by defining the == operator) to ensure correct object comparison.
Example implementation of Hashable for a structure:
struct User: Hashable {
let id: Int
let name: String
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id
}
}
In this example, the uniqueness of the User object is determined by the id field. This allows using User in sets and dictionaries, providing efficient storage and lookup by hash value.