Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Dictionary [String:String] to NSMutableDictionary?

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
like image 532
fuzzygoat Avatar asked May 20 '15 15:05

fuzzygoat


People also ask

How do you convert NSDictionary to NSMutableDictionary?

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.

What is NSDictionary in Swift?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.

Is it possible to use a custom struct as a dictionary key Swift?

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.


2 Answers

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)
like image 91
Airspeed Velocity Avatar answered Sep 28 '22 18:09

Airspeed Velocity


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
like image 37
Zell B. Avatar answered Sep 28 '22 19:09

Zell B.