如何将String值转换为枚举

时间:2014-12-08 09:54:50

标签: ios swift enums

如何将String值转换为String类型的枚举?

我的枚举定义如下:

enum TemplateSlotType : String {
    case Default = ""
    case Recommendation = "recommendation"
}

我想将字符串“recommended”转换为类型.Recommendation

1 个答案:

答案 0 :(得分:0)

我在Stack Overflow上找不到答案,但确实找到了答案。

这也适用于其他枚举类型:

enum Lets : String {
    case X = "x"
    case Y = "y"
    case Z = "z"
}

var zz = Lets.fromRaw("z")
zz! == .Z // true
println(Lets.Y.toRaw())

有关详细信息,请结帐:http://ericasadun.com/2014/08/27/swift-converting-values-to-enumerations/

我的最终实施:

if let slotType = json["type"].object as? String {
    type = TemplateSlotType(rawValue: slotType)!
}
相关问题