NSDictionary, how to store and read enum values?

How to save and read enum values ​​in NSDictionary in Swift.

I have identified several types

enum ActionType {
    case Person
    case Place
    case Activity    
}

Write enumeration to dictionary

myDictionary.addObject(["type":ActionType.Place])

"AnyObject does not have a name with a name"

Read

var type:ActionType = myDictionary.objectForKey("type") as ActionType

"Type" ActionType "does not conform to the protocol" AnyObject ""

I also tried to wrap ActionType as NSNumber / Int, which didn’t quite work. Any tips on properly storing and reading enum values ​​in NSDictionaries?

+4
source share
1 answer

, NSDictionary ( - ). NSNumber, toRaw , :

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

//Extended

:

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

let typeValue = ActionType.fromRaw(tmpInt!)
println(typeValue!.toRaw())
+8

All Articles