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.
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