Swift Equatable

In Swift, an Equatable is a protocol that allows two objects to be compared using the == operator. 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 {
  ...
}  

Here, we have conformed the Employee struct to the Hashable protocol.

Now when we create instances of Employee, the protocol will provide hash values to the instances.


Example: Swift Equatable Protocol

Output

obj1 and obj2 are not equal

Here, the code obj1 == obj2 evaluates to false because obj1 and obj2 have different values for the name property. Hence, the else block is executed.

Note: A hash value is a long integer that varies based on the system you are using, so you might get different values for the same code.


Compare Instances using Hashable Protocol

Output

obj1 and obj2 are equal
obj1 and obj3 are not equal

In the above example, we have created three objects: obj1, obj2, and obj3 of the Employee struct.

Here, the code obj1 == obj2 returns true because both objects have the same value for properties name and salary.

Similarly, the code obj1 == obj3 returns false because both objects have the different values for properties name and salary.


Equatable Function

In the above example, we have compared all the properties of the struct.

However, sometimes we may want to compare selective properties of the type. In this case, we may use the equatable function inside the type. For example,

static func == (lhs: Employee, rhs: Employee) -> Bool {
    return lhs.salary == rhs.salary 
}

Here, lhs.salary == rhs.salary will only compare the salary property of two given objects.


Use of Equatable Function

Output

obj1 and obj2 are equal

In the above example, we have used the ==() function to compare two instances on the basis of the salary property,

static func == (lhs: Employee, rhs: Employee) -> Bool {
    return lhs.salary == rhs.salary 
}

Here, the salary of ob1 and obj2 are the same, so the if block is executed..

If we provided the different value for salary, the else block would have been executed.