Mikk Rätsep
Mikk Rätsep

Reputation: 512

Swift nested enum common type

Is there a cleaner or a shorter way to write the following?

protocol AProtocol {}

enum AnEnum {
 enum NestedEnum1: AProtocol {
    case A1, B1
  }

  enum NestedEnum2: AProtocol {
    case A2, B2
  }
}

func makeItRain(_ rain: AProtocol)

The dream would be to just write the following –

func makeItRain(_ rain: AnEnum)

– that would accept NestedEnum1 and NestedEnum2 as input (without them having to conform to the AProtocol).

Upvotes: 0

Views: 554

Answers (1)

user28434'mstep
user28434'mstep

Reputation: 6600

enum AnEnum {
    enum NestedEnum1 {
        case A1, B1
    }

    enum NestedEnum2 {
        case A2, B2
    }

    case nestedEnum1(NestedEnum1)
    case nestedEnum2(NestedEnum2)
}

and in your makeItRain func you switch with .nestedEnum1 and nestedEnum2 cases.

// Well you have to wrap AnEnum.NestedEnum1 and AnEnum.NestedEnum2 in those cases of AnEnum tho.

Upvotes: 1

Related Questions