Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary, how to store and read enum values?

How can I store and read enum values in a NSDictionary in Swift.

I defined a few types

enum ActionType {
    case Person
    case Place
    case Activity    
}

Write enum to dictionary

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

"AnyObject does not have a member named key"

Read

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

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

I also tried wrapping the ActionType as NSNumber/Int which didn't quite work. Any advice on how to correctly store and read enum values in NSDictionaries?

like image 433
Bernd Avatar asked Sep 19 '14 10:09

Bernd


1 Answers

It's complaint because you cannot save values type to NSDictionary (enums is a value type). You have to wrap it to a NSNumber but remember to call toRaw on this enum, try this:

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

// Extended

This is how to access it step by step:

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

let typeValue = ActionType.fromRaw(tmpInt!)
println(typeValue!.toRaw())
like image 196
Greg Avatar answered Oct 13 '22 21:10

Greg