0

我有一个带有关联值的枚举。此外,每个值都有一个字符串描述。我怎样才能得到所有案例的描述?

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

2 回答 2

3

您可以使您的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: ", ")
    }
}
于 2019-09-09T12:14:09.903 回答
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)
于 2019-09-09T12:12:32.223 回答