0

I have an enum with associated values. In addition, every value has a String description. How can I get description of all the cases?

enum MyEnum {

    case caseA(data: [DataOfTypeA])
    case caseB(data: [DataOfTypeB])
    case caseC(data: [DataOfTypeC])
    case caseD(data: [DataOfTypeD])

    var typeDescription: String {
        switch self {
        case .caseA:
            return "caseA"
        case .caseB:
            return "caseB"
        case .caseC:
            return "caseC"
        case .caseD:
            return "caseD"
        }
    }
}

The thing I am looking for is:

"caseA, caseB, caseC, caseD"
Luda
  • 7,282
  • 12
  • 79
  • 139
  • You can't, unless you actually create each case with a different array. – Sweeper Sep 09 '19 at 12:07
  • Due to the associated data, I don't think you can get any help from the compiler. You may have to make do with simply `static var typeDescription = "caseA, caseB, caseC, caseD"` and having to manually maintain it as the enum evolves. – Chris Sep 09 '19 at 12:08
  • Wow I didn't realize enums in swift had this limitation :( – Carson Holzheimer Jul 26 '22 at 01:00

2 Answers2

3

You can make your enum conform to CaseIterable, then simply iterate through allCases to create typeDescription.

enum MyEnum: CaseIterable {
    case caseA(data: [Int])
    case caseB(data: [String])
    case caseC(data: [Date])
    case caseD(data: [Data])

    static var allCases: [MyEnum] = [.caseA(data: []), .caseB(data: []), .caseC(data: []), .caseD(data: [])]

    var caseDescription: String {
        switch self {
        case .caseA:
            return "caseA"
        case .caseB:
            return "caseB"
        case .caseC:
            return "caseC"
        case .caseD:
            return "caseD"
        }
    }

    static var typeDescription: String {
        return allCases.map {$0.caseDescription}.joined(separator: ", ")
    }
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
0

Imagine you have this variable:

let myEnum = MyEnum.caseA(data: [])

for accessing associated values:

switch myEnum {
case .caseA(let data): print(data)
case .caseB(let data): print(data)
case .caseC(let data): print(data)
case .caseD(let data): print(data)
}

for accessing typeDescription:

print(myEnum.typeDescription)

Or for any case without having a variable:

print(MyEnum.caseA(data: []).typeDescription)
Shadi Ghelman
  • 123
  • 1
  • 5