从NSDictionary Swift设置枚举

时间:2014-10-13 10:28:27

标签: ios xcode types swift enums

我将信息存储在plist文件中,我将其放入字典中。

我的课程设置如下:

enum componentPostion {
    case upperLeft, UpperRight, lowerLeft, lowerRight
}

我已经声明了一个类型为componentPostion的var

var isPosition: componentPostion

然后我可以从字典中的值设置枚举,而不必使用switch语句等编写函数。我已经尝试了这个没有运气

isPosition = componentInfo["Type"] as componentPostion

1 个答案:

答案 0 :(得分:1)

您可以通过从您想要保留的类型继承枚举来使用原始值,在您的情况下我假设它是字符串:

enum componentPostion : String{
    case upperLeft = "upperLeft"
    case upperRight = "upperRight"
    case lowerLeft = "lowerLeft"
    case lowerRight = "lowerRight"
}

然后您可以使用fromRaw()获取枚举案例:

let isPosition = componentPostion.fromRaw("upperLeft")

toRaw()获取其字符串表示

isPosition.toRaw()

注意fromRaw()返回一个可选项,以防参数与为枚举定义的任何原始值不匹配

建议阅读:Raw Values