简体   繁体   中英

Enumeration on enums with associated values - Swift

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"

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: ", ")
    }
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM