I have an enum defined as follows
enum Fruit {
case Apple(associatedValue: String)
case Orange(associatedValue: String)
}
I have a function that takes an argument of type Fruit
func printNameOnly(fruit: Fruit) {
}
In this function I want to get the enum case as a string, i.e. I want to get the string "Apple" or "Orange" without regard to whatever the associated value is. Is this possible with Swift?
I could obviously write a function which takes the fruit enum and returns a string using a case statement, but I am trying to find a way to avoid that since the string I want is the enum case name itself.
For instance, you might describe a weather enum that lists sunny, windy, and rainy as cases, but has an associated value for cloudy so that you can store the cloud coverage. Or you might describe types of houses, with the number of bedrooms being an associated integer.
The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so.
The Problem with Associated Values We had to do this because Swift doesn't allow us to have both: raw values and associated values within the same enum. A Swift enum can either have raw values or associated values.
Try this (Swift 3.1). Covers associated or regular cases.
enum Fruit {
case banana
case apple(String)
case orange(String)
var label:String {
let mirror = Mirror(reflecting: self)
if let label = mirror.children.first?.label {
return label
} else {
return String(describing:self)
}
}
}
print(Fruit.banana.label) // "banana"
print(Fruit.apple("yum").label) // "apple"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With