Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enumeration name when using associated values

Tags:

enums

swift

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.

like image 562
Puneet Avatar asked Feb 13 '16 00:02

Puneet


People also ask

Can you give useful examples of enum associated values?

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.

What are enum associated values?

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.

Can associated values and raw values coexist in Swift enumeration?

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.


1 Answers

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"
like image 178
David James Avatar answered Nov 15 '22 19:11

David James