In Swift, the == operator is used to check the equality of two values. In order for this operator to be used with custom types, the type must conform to the Equatable protocol and implement the static function ==.
The implementation should be symmetric and transitive. Example:
struct Person: Equatable { let name: String let age: Int static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age } }
It's important to remember that if your type does not implement ==, then attempting to compare two such instances will lead to a compilation error.
Question: If a struct or class conforms to the Equatable protocol, why can the == operator sometimes not need to be explicitly implemented?
Answer: For structs, if all properties also conform to Equatable, Swift automatically synthesizes the implementation of the == operator. But if the type has properties that are not Equatable, or if the type is a class with custom inheritance, synthesis will not occur, and the operator will need to be implemented manually.
struct Point: Equatable { var x: Int var y: Int // No need to implement ==, it is synthesized automatically }
Story
In one project, a developer added a property of type
UIImageto a struct that already conformed toEquatable. A compilation error occurred becauseUIImagedoes not conform toEquatable, so the==operator could not be synthesized for the struct automatically. The solution was to implement the==operator manually, comparing only the properties that are significant for the logic.
Story
An error occurred after adding a new property to the struct, but forgetting to include its comparison in the custom
==operator. This led to incorrect logic when working with collections and bugs in a custom filter.
Story
In the project, a custom class was written without implementing
Equatable, but it was attempted to be used in a Set. This led to a runtime error since Set requires elements to be unique (and thusEquatable).