【发布时间】:2017-06-30 02:50:58
【问题描述】:
如何从传递键值的枚举中获取原始值?必须适用于像枚举类型扩展一样工作的任何枚举类型。 欢迎任何镜面反射、可映射或 RawRepresentable 解决方案。
我想要这样的东西:
enum Test : String {
case One = "1"
}
Test.rawValueFromKey(keyValue: "One") // Must return "1"
// I don't want the solution below, I must get the rawValue through the key name as String.
Test.One.rawValue
我确实需要将键名作为字符串传递给 rawValue。否则,我将需要进行切换或许多 if/else 条件。我有一个很大的枚举,我不想检查例如在开关中传递的字符串并传递Test.One.rawValue。我想直接通过键作为字符串获取 rawValue,就像在字典中一样。
我也不想要下面的代码,因为我有一个包含 40 个项目的枚举,我认为切换 40 个项目很难看。
switch keyValue {
case "One":
return Test.One.rawValue
break
}
我想要这样的东西:
func rawValueFromKey (keyValue: String) -> Test {
// code here to get the rawValue through the keyValue as String
// return the proper Test Enum
}
我尝试了一些可能的解决方案,使用镜像反射和枚举迭代通过 keyValue 找到 rawValue,但没有奏效。
请在 Swift 2 和 3 中给出解决方案。
谢谢
【问题讨论】:
-
Test.One.rawValue -
stackoverflow.com/search?q=%5Bswift%5D+enum+rawValue 恐怕你自己还没有付出最少的努力。
-
Swift Language Guide : Enumerations 请阅读原始值部分。
-
你们没有理解我的问题,我只是编辑了我的问题以使自己清楚。我需要从键名中获取 rawValue 作为字符串。想象一下,您有一个通用函数,您将 Any Enum Type 和一个键名作为 String 传递,它将在没有任何 switch/if/else 条件的情况下获取原始值。它直接通过键名获取。
-
FWIW,这闻起来是糟糕的设计实现。我看不到这个的实际用例。
标签: ios swift mobile-development