Swift Equatable on a protocol
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction to Swift Equatable
In Swift, Equatable
is a protocol that allows types to be compared for equality. When a type conforms to the Equatable
protocol, it must implement the ==
operator, which checks for equality between two instances of that type. Making a type equatable is essential for tasks like checking if two objects are the same, filtering collections, and using types as dictionary keys. This article delves into how you can make a protocol conform to Equatable
, allowing all your custom types adhering to that protocol to automatically gain the benefits of equatability.
Why Equatable?
Before diving into making a protocol equatable, it's necessary to understand why Equatable
is fundamental in Swift programming:
- Comparison: Let's you easily compare two instances using the
==operator. - Filtering: Enable use cases such as filtering arrays with
containsandremove. - Sets and Dictionaries: Essential for unique collections types like
Setand dictionary keys. - Assertions: Useful for checking if two values in tests are equal.
Making a Protocol Equatable
To define a protocol with Equatable
, we can use protocol extensions. A protocol extension in Swift allows us to provide default behavior for protocols. When all the conforming types can be equated based on shared properties, a protocol extension makes sense.
Example
Imagine a protocol IdentifiablePerson
, which requires a unique id
property for identification. We can make this protocol conform to Equatable
by leveraging the id
for comparison.
IdentifiablePersonis a protocol that any person type can adopt.- By extending
IdentifiablePerson, we provide a default implementation of==, comparing theid. - Relevant Properties: Choose the properties that matter for equality. In the example given, the
idserves as the unique identifier. - Complex Types: If your protocol is intended for complex structures, ensure all underlying types also conform to
Equatable. - Protocol Composition: Protocols can inherit from or combine with other protocols. If making a protocol composable, ensure logical equatability.

