简体   繁体   English

快速枚举镜像获取关联值名称

[英]swift enum mirror get associated value name

I need to get the name of enum associated value.我需要获取枚举关联值的名称。

for example:例如:

enum App{
    case iOS(version:String)
    case android(version:String, build:Int)
}
let iosApp = App.iOS(version:"2.30.11")
let androidApp = App.android(version:"2.30.11",build:101)
let iosMirror = Mirror(reflecting: iosApp)
for case let (key?, value) in iosMirror.children {
        print("\(key)-\(value)") //this will print:iOS-2.30.11,missing the value name-"version",the string "version" was I need.
}
let androidMirror = Mirror(reflecting: androidApp)
for case let (key?, value) in androidMirror.children {
        print("\(key)-\(value)") //this will print:android-(version:"2.30.11",build:101)
}

question: I want get the associated value name "version" of iosApp from iosMirror,How should i do?问题:我想从iosMirror获取iosApp的关联值名称“version”,我该怎么做? or using other way(not Mirror) to get strings "version".或使用其他方式(不是镜像)来获取字符串“版本”。

Not sure if this is what you are after but you could let your enum implement CustomStringConvertible to get a specific output. 不知道这是您要追求的,但是您可以让您的枚举实现CustomStringConvertible以获得特定的输出。

enum App : CustomStringConvertible {
    var description: String { get {
        switch self {
            case .iOS(version: let v):
                return "version: \(v)"
            case .android(version: let v, build: let b):
                return "version: \(v) build: \(b)"
            }
        }
    }

    case iOS(version: String)
    case android(version:String, build:Int)
}

let iosApp = App.iOS(version:"2.30.11")
let androidApp = App.android(version:"2.30.11",build:101)

print(iosApp)
print(androidApp)

iOS-(version: "2.30.11") android-(version: "2.30.11", build: 101)gets printed with Xcode10(Swift4.2) so it is a bug from an older version. iOS-(版本:“ 2.30.11”)Android-(版本:“ 2.30.11”,内部版本:101)使用Xcode10(Swift4.2)打印,因此这是旧版本的错误。

-@Purpose -@目的

I tested this code in Xcode 10-beta 6,it print iOS-(version: "2.30.11"). 我在Xcode 10-beta 6中测试了此代码,它打印的是iOS-(版本:“ 2.30.11”)。 this question solved. 这个问题解决了。

thanks @Purpose. 谢谢@目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM