0

Context

I have an Enum where one of its Cases has an Optional Protocol Type as one of its Associated Types. Since adding this new Associated Type, I get the following Compiler Error:

Compiler Error #1: Type 'MyEnum' does not conform to protocol 'Equatable'

Compiler Error #2: Type 'MyEnum' does not conform to protocol 'Hashable'


Code

protocol Component { ... }

enum MyEnum: Hashable, Identifiable {
    var id: Int { hashValue }

    case myCase1
    case myCase2(value: Int? = nil)
    case myCase3(component: (any Component)? = nil) // Adding this Case breaks the Code.
}

Question

How can I solve the Compiler Errors above and support an Optional Protocol Type as an Associated Type for an Enum Case?

christophriepe
  • 1,157
  • 12
  • 47
  • @Sweeper No, `Component` has a few `Type Requirements`, but since they are not used in this example, I left them out for clarity. – christophriepe Sep 08 '22 at 08:04
  • Note that `any Component` does not conform to `Hashable`, even if you say `protocol Component: Hashable`. [Protocols do not conform to other protocols,](https://stackoverflow.com/q/33112559/5133585) especially those that have type requirements. See the link for why what you are trying to do does not make sense. – Sweeper Sep 08 '22 at 08:10
  • @Sweeper Thanks for your answer. Does this mean, it is impossible to use a `Protocol Type` as an `Associated Type` for an `Enum Case` in `Swift`? There must be a workaround? – christophriepe Sep 08 '22 at 09:37
  • It is possible if your protocol doesn't have type requirements. It does not *make sense* to do so, for the reasons mentioned in the link. – Sweeper Sep 08 '22 at 09:42

0 Answers0