【问题标题】:swift enum mirror get associated value name快速枚举镜像获取关联值名称
【发布时间】:2019-02-07 19:36:22
【问题描述】:

我需要获取枚举关联值的名称。

例如:

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)
}

问题:我想从iosMirror获取iosApp的关联值名称“version”,该怎么做?或使用其他方式(不是镜像)来获取字符串“版本”。

【问题讨论】:

  • 我不确定这是否可能,因为 Swift 不区分单元素元组及其(唯一)元素。
  • 谢谢,是否存在其他方式(不使用镜像反射)来获取字符串“版本”?
  • iOS-(version: "2.30.11") android-(version: "2.30.11", build: 101)使用 Xcode10(Swift4.2) 打印,所以它可能是旧版本的错误。

标签: swift enums mirror associated-value


【解决方案1】:

iOS-(版本:“2.30.11”)android-(版本:“2.30.11”,构建:101)获取 使用 Xcode10(Swift4.2) 打印,所以这是旧版本的错误。

-@目的

我在 Xcode 10-beta 6 中测试了这段代码,它打印 iOS-(version: "2.30.11")。 这个问题解决了。

感谢@Purpose。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2017-08-20
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多