Junior — Middle
What principles and requirements should be considered when creating a structure or class implementing the Equatable protocol?
sobes.tech AI
Answer from AI
When implementing the Equatable protocol in a struct or class, you need to:
- Define a static
==method that compares two instances of the type and returnstrueif they are considered equal. - Compare all significant properties that affect object equality.
- Ensure the comparison is symmetric, reflexive, and transitive.
Example implementation for a struct:
struct User: Equatable {
let id: Int
let name: String
static func == (lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id && lhs.name == rhs.name
}
}
If all properties already conform to Equatable, the compiler can automatically generate the implementation.