Home > Mobile >  Swift enum conformance to Equatable when result type used as associated value: Type doesn't con
Swift enum conformance to Equatable when result type used as associated value: Type doesn't con

Time:07-26

struct Book: Equatable {
    var book: String
}

enum BookAction: Equatable {
    case dataResponse(Result<Book, Error>)
}

I'm running swift version 5.6.1. I'm trying to understand why I'm getting an error that "type 'BookAction' does not conform to protocol 'Equatable'". While I can get it to work if I add a static func == (lhs: BoockAction, rhs: BookAction) -> Bool to the enum, I thought that the compiler would generate the equatable code behind the scenes like it does for the struct Book. It seems like it has everything needed to do that.

CodePudding user response:

Enum can automatically conform to Equatable if its associated values conform to Equatable, from docs:

For an enum, all its associated values must conform to Equatable. (An enum without associated values has Equatable conformance even without the declaration.)

And the Result<Success, Failure> only conform to Equatable when

Success conforms to Equatable, Failure conforms to Equatable, and Failure conforms to Error.

Your result's failure is only conform to Error and Error is not Equatable yet. You can try to replace your Error with a type that conforms to both Error and Equatable

enum BookAction: Equatable {
    case dataResponse(Result<Book, ActionError>)
}

struct ActionError: Error, Equatable { }

Ref:

https://developer.apple.com/documentation/swift/equatable https://developer.apple.com/documentation/swift/result

  • Related