如何不更改 Swift 中的父 NSMutableArray

How not to change the parent NSMutableArray in Swift

我有一个 NSMutableArray,我只想将它复制到另一个 NSMutableArray 并更改第二个

示例代码

let one: NSMutableArray = NSMutableArray();
one.addObject(9);

var two: NSMutableArray = NSMutableArray();

two = one;
two.addObject(4);
one.addObject(2);

println(two); // "(\n    9,\n    4,\n    2\n)" - the 2 should not be here
println(one);// "(\n    9,\n    4,\n    2\n)" - the 4 should not be here

我试试

two = one.copy() as! NSMutableArray; // but this give an error

//更新 // 如果取而代之的是一个简单的数字,则有 NSMutableDictionary

let one: NSMutableArray = NSMutableArray();

for (var i = 0; i < 2; i++){
    let dic: NSMutableDictionary = NSMutableDictionary();
    dic["type"] = "free";
    dic["value"] = i;
    one.addObject(dic);
}

var two: NSMutableArray = one.mutableCopy() as! NSMutableArray;

two[0].setObject("used", forKey: "type");
println(two);
println(one); // one[0] - used, but it should be free

// 这是复制旧数组的方法

let two: NSMutableArray = NSMutableArray(array: one);