NSDictionary,如何存储和读取枚举值?

Ber*_*rnd 4 enums nsdictionary ios swift

如何在Swift中的NSDictionary中存储和读取枚举值.

我定义了几种类型

enum ActionType {
    case Person
    case Place
    case Activity    
}
Run Code Online (Sandbox Code Playgroud)

枚举写入字典

myDictionary.addObject(["type":ActionType.Place])
Run Code Online (Sandbox Code Playgroud)

"AnyObject没有名为key的成员"

var type:ActionType = myDictionary.objectForKey("type") as ActionType
Run Code Online (Sandbox Code Playgroud)

"类型'ActionType'不符合协议'AnyObject'"

我也尝试将ActionType包装为NSNumber/Int,但这并不常用.关于如何在NSDictionaries中正确存储和读取枚举值的任何建议?

Gre*_*reg 8

这是抱怨,因为您无法将值类型保存到NSDictionary(枚举是值类型).你必须将它包装到NSNumber但记得在这个枚举上调用toRaw,试试这个:

enum ActionType : Int {
    case Person
    case Place
    case Activity
}
var myDictionary = NSDictionary(object:NSNumber(integer: ActionType.Place.toRaw()), forKey:"type")
Run Code Online (Sandbox Code Playgroud)

//扩展

这是如何逐步访问它:

let typeAsNumber = myDictionary["type"] as? NSNumber
let tmpInt = typeAsNumber?.integerValue

let typeValue = ActionType.fromRaw(tmpInt!)
println(typeValue!.toRaw())
Run Code Online (Sandbox Code Playgroud)