Equatable Protocol in Swift

Shantaram Kokate
2 min readNov 3, 2020

--

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, Booland 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 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 Equatableprotocol.

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 property
  • emoji 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.

If you like this post, please share and give claps so others can find it 👏👏

You can follow me on Medium for updated articles. Also, connect with me on LinkedIn, Twitter.

If you have any comments, questions, or recommendations, feel free to post them in the comment section below!👇

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

--

--

Shantaram Kokate
Shantaram Kokate

No responses yet

Write a response