Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Swift dictionary with enum keys to an NSDictionary?

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?

like image 743
eliocs Avatar asked Dec 12 '25 23:12

eliocs


2 Answers

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.

like image 90
Dharmesh Kheni Avatar answered Dec 15 '25 14:12

Dharmesh Kheni


None of them (StringEnum, String, Dictionary) are obj-c types, therefore you cannot do that implicitly. You definitely need a loop for that.

like image 29
Mert Buran Avatar answered Dec 15 '25 12:12

Mert Buran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!