Reputation: 231
I want to print the raw value of nested enums. For example, if I have a top level Food enum with multiple cases (for simplicity let's just say two: fruit, veggie), each of which are string enums (Fruit: String, Vegetable: String, etc), is there a way to print the inner associated values without doing a switch statement one the top level enum?
My current code is below. As you can see, the more cases I add to Food, the more redundant code will end up in var description. I'd like to write one action for all cases that prints the rawValue of the inner enums.
Is that possible without the switch?
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"
}
Upvotes: 1
Views: 362
Reputation: 773
Is that possible without the switch?
No, this is not currently possible.
Workaround: I've noticed a pattern with your enum case names. The raw values of each are all capitalized versions of the case name i.e. case apple = "Apple"
. If this pattern always holds, you can use the following code:
var description: String { ("\(self)".split(separator: ".").last?.dropLast().capitalized)! }
Which will produce:
print(Foods.fruit(.apple).description) // Apple
Upvotes: 2