枚举具有关联值的枚举-Swift

时间:2019-09-09 11:58:14

标签: swift enums associated-value

我有一个带有关联值的枚举。此外,每个值都有一个String描述。如何获得所有情况的描述?

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"
        }
    }
}

我要寻找的是:

"caseA, caseB, caseC, caseD"

2 个答案:

答案 0 :(得分:2)

您可以使您的enum符合CaseIterable,然后简单地遍历allCases来创建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: ", ")
    }
}

答案 1 :(得分:0)

想象一下您有这个变量:

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

用于访问关联值:

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)
}

用于访问typeDescription

print(myEnum.typeDescription)

或者在任何情况下没有具有变量:

print(MyEnum.caseA(data: []).typeDescription)