Junior
What is Hashable in Swift?
sobes.tech AI
Answer from AI
The Hashable protocol allows objects to be used in hash-based collections such as Set and Dictionary. The conforming type must provide a hashValue that generates a hash for the object.
Main points:
- Types conforming to
Hashablegenerate an integer value representing their hash. - If two objects are equal (
==), their hash values must be the same. - If two objects have the same hash value, they are not necessarily equal.
- Swift automatically synthesizes
Hashableconformance for structs and enums if all their members conform toHashable. - For classes or custom structs with non-
Hashablemembers,hash(into:)must be implemented manually.
Example of manual implementation:
struct MyStruct {
let id: Int
let name: String
}
extension MyStruct: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
}
}