问题描述
我想打印嵌套枚举的原始值。例如,如果我有一个带有多个案例的顶级Food枚举(为简单起见,我们只说两个:水果,蔬菜),每种都是字符串枚举(水果:String,vegetable:String等),有没有办法打印内部关联值,而无需在顶级枚举中做一个switch语句?
我当前的代码如下。如您所见,我向Food添加的案例越多,越多的冗余代码将最终出现在var描述中。我想为所有情况写一个动作,以打印内部枚举的rawValue。
没有开关就可以吗?
enum Foods {
case fruit(Fruit)
case veggie(vegetable)
var description: String { // this is what I'd like to replace
switch self {
case .fruit(let type):
return type.rawValue // since every case will look like this
case .veggie(let type):
return type.rawValue
}
}
}
enum Fruit: String {
case apple = "Apple"
case banana = "Banana"
}
enum vegetable: String {
case carrot = "Carrot"
case spinach = "Spinach"
}
解决方法
没有开关就可以吗?
否,目前无法实现。
解决方法: 我注意到您的枚举案例名称存在一个模式。每个实例的原始值都是案例名称i.e. case apple = "Apple"
的所有大写形式。如果此模式始终有效,则可以使用以下代码:
var description: String { ("\(self)".split(separator: ".").last?.dropLast().capitalized)! }
哪个会产生:
print(Foods.fruit(.apple).description) // Apple