Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

enums

ios

swift

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?

like image 470
Shane D Avatar asked Mar 03 '26 22:03

Shane D


1 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)
}
like image 131
Subramanian Mariappan Avatar answered Mar 05 '26 10:03

Subramanian Mariappan