Swift Hashable- compare instances

Ramesh Chavan
2 min readOct 4, 2022

--

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
4997634560615333199
Same 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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ramesh Chavan
Ramesh Chavan

Written by Ramesh Chavan

Like to work on iOS, Android, UIPath and Graph DB

No responses yet

Write a response