I can't convert a Swift dictionary to an NSDictionary
. I'm using a Swift enumerate as the key of my dictionary:
enum StringEnum : String {
case Lemon = "lemon"
case Orange = "orange"
}
var swiftDictionary = [StringEnum: AnyObject]()
swiftDictionary[.Lemon] = "string value"
swiftDictionary[.Orange] = 123
When I try to convert it to a NSDictionary
with the as
keyword:
let objcDictionary: NSDictionary = swiftDictionary as NSDictionary
I get the compiler error:
'[StringEnum : AnyObject]' is not convertible to 'NSDictionary'
Can these types of dictionaries be converted or do I need to loop the Swift dictionary and create an NSDictionary
manually?
I think if your dictionary have enum values then you can not convert it to NSDictionary
but another way to do that is:
//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]
Hope this will help.
None of them ( StringEnum
, String
, Dictionary
) are obj-c
types, therefore you cannot do that implicitly. You definitely need a loop for that.
It is complaint because you cannot save values type to NSDictionary (enums is a value type). You have to wrap it to a NSNumber or any other type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.