Equatable Protocol in Swift
What is Equatable Protocol?
Equatable the protocol used to compared two objects.
Many types in the Swift standard library already conform to the
Equatable protocol such as
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, make
Equatabel them protocol compliant.
Then the error disappears. The results were as expected.
Apparently, when the type conforms
Equatableto 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
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 ==.
nameIgnore the property
emojiCompare 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 returned
true because they are oranges.