Equatable Protocol in Swift
What is Equatable Protocol?
The Equatable
the protocol used to compared two objects.
Many types in the Swift standard library already conform to the Equatable
protocol such as String
, Int
, Bool
and Double
. But how do we make our own types conform?
Let’s look at the following example:
If there is such a custom type
Apple and banana are two different fruit. let's compare if they are the same
If you look at it, it may be false but an error message was displayed. Binary operator’==’ cannot be applied to two’ Fruit’ operands.

To ensure that objects can be compared to see if they are the same, makeEquatabel
them protocol compliant.
Then the error disappears. The results were as expected.
Apparently, when the type conforms Equatable
to the protocol, it automatically compares whether all member properties are the same.
Control the conditional comparison:
In order to compare two different Objects based on properties, we can achive this by Equatable
protocol.
let’s drive into an example
Now we have the same type of fruit. If you compare whether they are the same, you will find that these are not the same. although these oranges are of different varieties, I feel like treating them as the same fruit
To explicitly compare two objects based on their properties It would be nice if we implement the static func ==
.
name
Ignore the propertyemoji
Compare only properties
Implement the == operator
==
Operators are used when comparing.
By implementing it as a static method, ==
the behavior of the operator can be customized for each type.
Let's return the result of comparing only the properties.
Now The result has changed.
Although the varieties are different, they returnedtrue
because they are oranges.