Junior — Middle
What methods does the Hashable protocol in Swift implement?
sobes.tech AI
Answer from AI
The Hashable protocol in Swift requires the implementation of the hash(into:) method, which takes one parameter — an inout Hasher object. In this method, you need to pass all properties that influence the uniqueness of the object into the hasher to generate a hash code.
Example:
struct Person: Hashable {
var name: String
var age: Int
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(age)
}
}
Additionally, to conform to Hashable, the type must also conform to Equatable, meaning it must implement the == operator. In most cases, the compiler automatically generates these methods if all properties are also Hashable and Equatable.