How to make a generic enum Equatable in Swift?

Viewed 2001

Having a generic enum Result<T>

enum Result<T> {
    case success(T)
    case error
}

How to make it conform to the Equatable protocol in Swift version 3 or higher?


I've tried the following:

extension Result: Equatable {
    static func ==<T: Equatable>(lhs: Result<T>, rhs: Result<T>) -> Bool {
        switch (lhs, rhs) {
        case let (.success(lhsVal), .success(rhsVal)):
            return lhsVal == rhsVal
        case (.error, .error):
            return true
        default:
            return false
        }
    }
}

However, this produces a compiler error: Type 'Result<T>' does not conform to protocol 'Equatable'

I've also tried the following:

extension Result: Equatable {
    static func ==(lhs: Result, rhs: Result) -> Bool {
        switch (lhs, rhs) {
        case let (.success(lhsVal), .success(rhsVal)):
            return lhsVal == rhsVal
        case (.error, .error):
            return true
        default:
            return false
        }
    }
}

However, this produces a compiler error: Binary operator '==' cannot be applied to two 'T' operands

2 Answers

Write this extension without implementation:

extension Result: Equatable where T: Equatable {}

When T conforms to Equatable, Result<T> would conform to Equatable automatically.

Related