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?
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With