I am trying to create and assign a Swift Dictionary
of type [String : String]
at the SKSpriteNode
property userData
which requires an NSMutableDictionary
. When I try this I get the error:
'[String : String]' is not convertible to 'NSMutableDictionary'
Can anyone 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
Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.
An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.
Any type that conforms to the Hashable protocol can be used as a dictionary's Key type, including all of Swift's basic types. You can use your own custom types as dictionary keys by making them conform to the Hashable protocol.
There’s no built-in cast for this. But instead you can use NSMutableDictionary
’s initializer that takes a dictionary:
var foundationDictionary = NSMutableDictionary(dictionary: dictionary)
One alternative answer to the answers above is to cast your dictionary to NSDictionary create a mutable copy of it and cast it to NSMutableDictionary. Too complicated, right ? Therefore I recommend creating new NSMutableDictionary from Dictionary this is just an alternative
var foundationDictionary = (dictionary as NSDictionary).mutableCopy() as! NSMutableDictionary
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