我有一个带有关联值的枚举。此外,每个值都有一个字符串描述。如何获取所有情况的描述?
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"
您可以使您的enum
符合CaseIterable
,然后简单地遍历allCase
以创建type描述
。
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: ", ")
}
}
想象一下你有这个变量:
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)
}
用于访问type描述
:
print(myEnum.typeDescription)
或者对于没有变量的任何情况:
print(MyEnum.caseA(data: []).typeDescription)