Enum with associated value does not conform to CaseIterable and throws error

Viewed 3937

The following enum works fine without any error.

enum EnumOptions: CaseIterable {
        case none
        case mild
        case moderate
        case severe
        case unmeasurable
}

When I try to add an associated value to one of the cases, it throws the following error "Type 'EnumOptions' does not conform to protocol 'CaseIterable'. Do you want to add protocol stubs?"

enum OedemaOptions: CaseIterable {
        case none
        case mild
        case moderate
        case severe
        case unmeasurable(Int)
}

After adding stubs,

enum OedemaOptions: CaseIterable {
        typealias AllCases = <#type#>

        case none
        case mild
        case moderate
        case severe
        case unmeasurable(Int)

What should be filled up in the placeholder to make the Enum conform to CaseIterable, since there is only 1 case with associated value and not all the cases?

2 Answers

Automatic synthesis does not work for enums with associated values. You need to provide a custom implementation of the allCases property. Try,

enum OedemaOptions: CaseIterable {
    static var allCases: [OedemaOptions] {
        return [.none, .mild, .moderate, .severe, .unmeasurable(-1)]
    }
    
    case none
    case mild
    case moderate
    case severe
    case unmeasurable(Int)
}

You forgot to account for all 18,446,744,073,709,551,616 Ints.

Also, each one is an Option, not an Options.

static var allCases: [OedemaOption] {
  [.none, .mild, .moderate, .severe]
  + (.min...(.max)).map(unmeasurable)
}
Related