Swift Dictionary [String: String] in NSMutableDictionary?

I am trying to create and assign a Swift Dictionary type [String : String] in the SKSpriteNode property userData , which requires NSMutableDictionary . When I try to do this, I get an error message:

 '[String : String]' is not convertible to 'NSMutableDictionary' 

Can someone point me in the right direction?

  // USER DATA var dictionary: [String : String] = Dictionary() dictionary["Orbit"] = orbit dictionary["Zone"] = zone dictionary["Impact"] = impact var foundationDictionary = dictionary as NSMutableDictionary neoSprite.userData = foundationDictionary 
+5
source share
4 answers

There is no built-in throw for this. But instead, you can use the NSMutableDictionary s initializer, which takes a dictionary:

 var foundationDictionary = NSMutableDictionary(dictionary: dictionary) 
+24
source

One alternative answer to the above answers is to cast the dictionary to NSDictionary, create a mutable copy of it, and pass it to NSMutableDictionary. Too complicated, isn't it? Therefore, I recommend creating a new NSMutableDictionary from the Dictionary, this is just an alternative

 var foundationDictionary = (dictionary as NSDictionary).mutableCopy() as! NSMutableDictionary 
+2
source

Can you try replacing this line:

 var foundationDictionary = dictionary as NSMutableDictionary 

With this code:

 var foundationDictionary = NSMutableDictionary(dictionary: dictionary) 
+1
source

Dictionaries

Create immutable dictionary

 let dictionary = ["Item 1": "description", "Item 2": "description"] 

Create a mutable dictionary

 var dictionary = ["Item 1": "description", "Item 2": "description"] 

Add a new pair to the dictionary

 dictionary["Item 3"] = "description" 
0
source

All Articles