Swift Hashable- compare instances
In Swift, a Hashable is a protocol that provides a hashValue
to our object. The hashValue
is used to compare two instances.

To use the hashValue
, we first have to conform (associate) the type (struct, class, etc) to Hashable property. For example,
struct Employee: Hashable {
...
}
Compare Instances using Hashable Protocol
// conform Employee to Hashable
struct Employee: Hashable {
var name: String
var salary: Int
}// initialize two objects with different property values
let obj1 = Employee(name: "Sabby", salary: 40000)
let obj2 = Employee(name: "Cathy", salary: 30000)print("Different hash value: ")
print(obj1.hashValue)
print(obj2.hashValue)// initialize two objects with same property values
let obj3 = Employee(name: "Lanny", salary: 50000)
let obj4 = Employee(name: "Lanny", salary: 50000)print("\nSame hash value: ")
print(obj3.hashValue)
print(obj4.hashValue)
Output
Different hash value:
3934953678767833906
4997634560615333199Same hash value:
1588129438168529318
1588129438168529318
However, sometimes we may want to compare selective properties of the type. In this case, we may use the hash function inside the type. For example,
func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
Here, the hash()
function uses hasher.combine()
to specify the property that we want to compare.
Use of Hash Function
struct Employee: Hashable {
var name: String
var salary: Int// create a hash() function to only compare salary property
func hash(into hasher: inout Hasher) {
hasher.combine(salary)
}}// initialize two objects with different values for salary property
let obj1 = Employee(name: "Sabby", salary: 349879)
let obj2 = Employee(name: "Sabby", salary: 422532)print(obj1.hashValue)
print(obj2.hashValue)
Output
3932232896576771782
743881919875172951