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

ios – NSDictionary,如何存储和读取枚举值?,第1张

概述如何在 Swift中的NSDictionary中存储读取枚举值. 我定义了几种类型 enum ActionType { case Person case Place case Activity } 将枚举写入字典 myDictionary.addObject(["type":ActionType.Place]) “AnyObject没有名为key的成员” 读 va 如何在 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中正确存储和读取枚举值的任何建议?

解决方法 这是抱怨,因为您无法将值类型保存到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? NSNumberlet tmpInt = typeAsNumber?.integerValuelet typeValue = ActionType.fromraw(tmpInt!)println(typeValue!.toRaw())
总结

以上是内存溢出为你收集整理的ios – NSDictionary,如何存储和读取枚举值?全部内容,希望文章能够帮你解决ios – NSDictionary,如何存储和读取枚举值?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1077063.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存