Floyd Resler
Floyd Resler

Reputation: 1786

iOS Swift Dictionary Cloning

I have an NSMutableDictionary that I make copies of. After I make the copies I want to change the values in each dictionary independently. However, when I change one all the others change. It's almost like the copies are just pointers back to the original. My code to set them is:

var nf = text?.toInt()!
var creatureInfo = NSMutableDictionary()
for var c = 0;c<nf;c++ {
    creatureInfo = NSMutableDictionary()
    creatureInfo = getCreature(name)
    creatureInfo.setValue("creature", forKey: "combat-type")
    combatants.append(creatureInfo)
}

I thought at doing creatureInfo = NSMutableDictionary() in the loop would work but it did not.

Upvotes: 2

Views: 73

Answers (2)

vacawama
vacawama

Reputation: 154603

I believe @zneak's answer is the way to go. If you must stick with NSMutableDictionary, then this should work:

var creatureInfo = getCreature(name).mutableCopy() as! NSMutableDictionary
creatureInfo["combat-type"] = "creature"
combatants.append(creatureInfo)

Upvotes: 0

zneak
zneak

Reputation: 138071

NSMutableDictionary is a reference type (it's a class, not a struct) from the Cocoa legacy. If it looks like the copies are just pointers back to the original, that's because they are: getCreature most likely always returns the same instance.

Use the Swift Dictionary type to get dictionaries that are treated as value types. You can declare one with the syntax [KeyType: ValueType].

var creatureInfo: [String: String] = getCreature(name) as! [String: String]
creatureInfo["combat-type"] = "creature"
combatants.append(creatureInfo)

Upvotes: 4

Related Questions