Junior — Senior
Why should you implement the Equatable protocol through an extension
livecode
Task condition
In Swift, it is often necessary for types to be comparable for equality. One convenient way to add such behavior is by declaring conformance to the Equatable protocol in an extension. This allows you to specify a condition under which a type conforms to the protocol only if its parameters also support Equatable. Below is an example where Result automatically implements the == operator if both Value and Error types are comparable.
extension Result: Equatable where Value: Equatable, Error: Equatable {
static func == (lhs: Result, rhs: Result) -> Bool {
switch (lhs, rhs) {
case .success(let lhsVal), .success(let rhsVal):
return lhsVal == rhsVal
case .failure(let lhsVal), .failure(let rhsVal):
return lhsVal == rhsVal
default:
return false
}
}
}