【问题标题】:NSDictionary, how to store and read enum values?NSDictionary,如何存储和读取枚举值?
【发布时间】:2014-11-13 22:52:59
【问题描述】:

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

我定义了几种类型

enum ActionType {
    case Person
    case Place
    case Activity    
}

写入枚举到字典

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

“AnyObject 没有名为 key 的成员”

阅读

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

“类型‘ActionType’不符合协议‘AnyObject’”

我还尝试将 ActionType 包装为 NSNumber/Int,但效果不太好。关于如何在 NSDictionaries 中正确存储和读取枚举值的任何建议?

【问题讨论】:

    标签: ios enums swift nsdictionary


    【解决方案1】:

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

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

    // 扩展

    这是逐步访问它的方法:

    let typeAsNumber = myDictionary["type"] as? NSNumber
    let tmpInt = typeAsNumber?.integerValue
    
    let typeValue = ActionType.fromRaw(tmpInt!)
    println(typeValue!.toRaw())
    

    【讨论】:

    • 哦,有道理。非常感谢您的解释。将字典值转回枚举的最佳方法是什么?我试过 var typeValue:ActionType = (myDictionary.objectForKey("type") as NSNumber).intValue ... 没用
    • @BerndPlontsch 请查看扩展答案。
    • 我虽然字典和数组接受任何对象作为值。这听起来像是属性列表的对象限制。
    • @Rivera 字典和数组接受任何对象,但 NSDictionaries 和 NSArrays 只接受对象,而不接受原始值。
    猜你喜欢
    • 2019-10-02
    • 2019-05-09
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多