Equatable Protocol in Swift

Batikan Sosun
Sahibinden Technology
2 min readApr 4, 2022

--

Photo by Luca Bravo on Unsplash

Equatable is a protocol that explicitly defines the semantics of equality and inequality in a way wholly separate from the question of identity.

In Swift, when you compare two strings variable using == the equality operator, you don’t need to conform Equatable protocol due to it is implemented by default.

The equatable protocol is a great way to compare two custom objects. Let’s create a simple example to understand the equatable protocol.

I created a struct called Planet. Planet struct has a name and a radius.

Before conforming Equatable protocol, if you compare two objects by the == equality operator, you will get the below error.

On the other hand, you can follow the below way.
However, nobody wants this due to too many equality logics.

We can add Equatable conformance through an extension, implementing the required type method for the == equality operator. This example will look like the below.

Conditional Conformance to Equality

In Equatable Protocol, another critical point is Conditional Conformance. That was improved in Swift 4.2, giving the capability to query a conditional conformance at the runtime
Let’s create an example. I will add a moons array to the Planet struct.

Finally, You will see the full of example code. Also, you can use the == equality operator for collections.

It can be converted to a conditionally conformed protocol, it works great like the below.

Thanks for reading, Have a nice day 🙌

Let’s connect on Twitter.

--

--

Batikan Sosun
Sahibinden Technology

Tweeting tips and tricks about #swift #xcode #apple Twitter @batikansosun Weekly Swift Blogging