Use Hashable Protocol in Swift
Written by Team Kodeco
The Hashable
protocol in Swift provides a way to define an object as hashable, which means it can be used as the key in a dictionary or as an element in a set.
Here is an example implementation of the Hashable
protocol in a custom data type Person
:
struct Person: Hashable {
let firstName: String
let lastName: String
let age: Int
func hash(into hasher: inout Hasher) {
hasher.combine(firstName)
hasher.combine(lastName)
hasher.combine(age)
}
}
In this example, you implemented the hash(into:)
function, which calculates the hash value of a Person
object based on its first name, last name, and age properties.
With this implementation, Person
objects can be used as keys in a dictionary or elements in a set, because they conform to the Hashable
protocol.
let person1 = Person(firstName: "John", lastName: "Doe", age: 30)
let person2 = Person(firstName: "Jane", lastName: "Doe", age: 25)
var personDict: [Person: String] = [:]
personDict[person1] = "Teacher"
personDict[person2] = "Doctor"
print(personDict[person1]) // Output: Optional("Teacher")
print(personDict[person2]) // Output: Optional("Doctor")