What is the Equatable Protocol in Swift?

Inspect your custom objects for equality

Abboskhon Shukurullaev
Clean Software
2 min readJul 14, 2020

--

Photo by Benjamin Wong on Unsplash

Today we will learn about a protocol that provides a clear way to find out if your custom objects are equal.

Without further ado, let’s explore Equatable protocol in practice.

Let’s Start

Say we have simple struct called StudentsBook:

But how can we make sure it’s the right student? In order to compare instances for equality we need to:

  • Adopt Equatable protocol
  • Provide an implementation for the == operator. Simply add a static == func that takes lhs (left-hand side) and rhs (right-hand side) parameters and returns a Bool that decides whether the two sides are equal or not.

By doing this, we’ve compared all instances and get a pure result.

However, in certain cases, there are requirements of a protocol that can be autogenerated for you. You only specify the name of protocol and don’t write == method on your own. The Swift compiler will autogenerate the implementation just by looking at data types.

Wrapping up

This is all you should know about Equatable protocol. I hope it was interesting!

Interested in other relative protocols? Feel free to visit my other relevant articles:

If you have any criticism, question, or suggestion, feel free to post them in the comment section below!

Thanks for reading.

--

--

Abboskhon Shukurullaev
Clean Software

iOS-developer. I have tons of knowledge to learn, and I am happy to share it during the period