当前位置 : 主页 > 手机开发 > ios >

ios – 如何将带有枚举键的Swift词典转换为NSDictionary?

来源:互联网 收集:自由互联 发布时间:2021-06-11
我无法将 Swift字典转换为NSDictionary.我使用Swift枚举作为我的字典的关键: enum StringEnum : String { case Lemon = "lemon" case Orange = "orange"}var swiftDictionary = [StringEnum: AnyObject]()swiftDictionary[.Lemon] =
我无法将 Swift字典转换为NSDictionary.我使用Swift枚举作为我的字典的关键:

enum StringEnum : String {
    case Lemon = "lemon"
    case Orange = "orange"
}

var swiftDictionary = [StringEnum: AnyObject]()
swiftDictionary[.Lemon] = "string value"
swiftDictionary[.Orange] = 123

当我尝试使用as关键字将其转换为NSDictionary时:

let objcDictionary: NSDictionary = swiftDictionary as NSDictionary

我收到编译器错误:

'[StringEnum : AnyObject]' is not convertible to 'NSDictionary'

可以转换这些类型的字典,还是需要循环Swift字典并手动创建NSDictionary?

我想如果你的字典有枚举值,那么你不能将它转换为NSDictionary,但另一种方法是:

//change the type of your dict to [String: AnyObject]()
var swiftDictionary = [String: AnyObject]()

//you can store rawValue as a key
swiftDictionary[StringEnum.Lemon.rawValue] = "string value"
swiftDictionary[StringEnum.Orange.rawValue] = 123

let objcDictionary = swiftDictionary as NSDictionary  //["lemon": "string value", "orange": 123]

希望这会有所帮助.

网友评论