Home > Mobile >  How to give a default implementations to a protocol implemented by an enum?
How to give a default implementations to a protocol implemented by an enum?

Time:10-07

I have an enum that implements a protocol:

protocol MyProtocol {
  func myFunction()
}

enum MyEnum: MyProtocol {
  case caseOne
  case caseTwo
  case caseThree
}

This protocol has only one method that can be implemented by default for all the enum's cases:

extension MyProtocol where Self == MyEnum {
  func myFunction() {
    // Default implementation.
  }
}

But I would like to create a default implementation for each case of the enum, something like this (PSEUDOCODE):

extension MyProtocol where Self == MyEnum & Case == caseOne {
  func myFunction() {
    // Implementation for caseOne.
  }
}

extension MyProtocol where Self == MyEnum & Case == caseTwo {
  func myFunction() {
    // Implementation for caseTwo.
  }
}

extension MyProtocol where Self == MyEnum & Case == caseThree {
  func myFunction() {
    // Implementation for caseThree.
  }
}

Is it possible?

CodePudding user response:

enum cases are not present in the type system in the way that you might be looking for: each case of an enum does not get its own type, and can't be discriminated against statically like this. There's also the issue that you can't give one type (MyEnum) more than one implementation which fulfills a protocol requirement, so this isn't possible from that aspect either; you'll need to write a single implementation with a switch inside.

  • Related