使用关联值时获取枚举名称

Pun*_*eet 5 enums swift

我的枚举定义如下

enum Fruit {
    case Apple(associatedValue: String)
    case Orange(associatedValue: String)
}
Run Code Online (Sandbox Code Playgroud)

我有一个函数,它接受类型为Fruit的参数

func printNameOnly(fruit: Fruit) {

}
Run Code Online (Sandbox Code Playgroud)

在这个函数中,我想把枚举的情况作为一个字符串,即我想得到字符串"Apple"或"Orange",而不考虑相关的值.Swift可以实现吗?

我显然可以编写一个函数,它接受水果枚举并使用case语句返回一个字符串,但我试图找到一种方法来避免这种情况,因为我想要的字符串是enum case name本身.

Dav*_*mes 9

试试这个(Swift 3.1).涵盖相关或常规案例.

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"
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 0

当枚举具有关联值时,打印它们将列出所有值以及枚举名称。例如:

let anApple = Fruit.Apple("myApple")
print(anApple)
Run Code Online (Sandbox Code Playgroud)

这将产生:

Apple("myApple")
Run Code Online (Sandbox Code Playgroud)

因此,要获取“Ap​​ple”,请提取第一个“(”之前的部分。

  • 我认为依赖默认描述生成的字符串表示形式会非常hacky。 (4认同)