iOS Swift Dictionary Cloning

时间:2015-07-31 20:38:51

标签: ios swift nsmutabledictionary

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.

2 个答案:

答案 0 :(得分:4)

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)

答案 1 :(得分:0)

我相信@ zneak的答案是要走的路。如果您必须坚持NSMutableDictionary,那么这应该有效:

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