结论写在最前面:
数组元素是struct时,复制数组后修改,以及修改指向数组元素的变量都不会影响到原来的数组;元素是class时则会。
详细的测试用例一图清楚明了。
测试代码
class Person : CustomDebugStringConvertible {
var debugDescription: String {
return "debug:\(age)"
}
var age : Int = 0
init(age:Int){
self.age = age
}
}
func forClass() {
var perArr = [Person]()
perArr.append(Person(age:12))
perArr.append(Person(age:13))
perArr.append(Person(age:14))
print("A:perArr = \(perArr)")
//perArr = [debug:12, debug:13, debug:14]
var copyArr = perArr
print("A:copyArr = \(copyArr)")
//A:copyArr = [debug:12, debug:13, debug:14]
//==============[case 1]=======================
//操作:对数组复制后,修改复制得到的数组的元素,
copyArr[1].age = 100
print("B:copyArr = \(copyArr)")
//B:copyArr = [debug:12, debug:100, debug:14]
print("B:perArr = \(perArr)")
//B:perArr = [debug:12, debug:100, debug:14]
//结果:原来数组的元素也会发生改变,两个输出结果里都是'debug:100';所以数组元素依然是引用
//==============[case 2]=======================
//操作:新建一个元素,把元素添加到数组后再修改该元素
let testP = Person(age:999)
copyArr.append(testP)
print("C:copyArr = \(copyArr)")
//C:copyArr = [debug:12, debug:100, debug:14, debug:999]
print("A:testP = \(testP)")
//A:testP = 999
testP.age = 888
print("D:copyArr = \(copyArr)")
//D:copyArr = [debug:12, debug:100, debug:14, debug:888]
//结果:数组的元素也会发生改变,输出结果里有'debug:888';所以数组元素依然是引用
}
struct User : CustomDebugStringConvertible {
var age : Int = 0
var debugDescription: String {
return "debug:\(age)"
}
}
func forStruct() {
var perArr = [User]()
perArr.append(User(age:12))
perArr.append(User(age:13))
perArr.append(User(age:14))
print("A:perArr = \(perArr)")
//perArr = [debug:12, debug:13, debug:14]
var copyArr = perArr
print("A:copyArr = \(copyArr)")
//A:copyArr = [debug:12, debug:13, debug:14]
//==============[case 1]=======================
//操作:对数组复制后,修改复制得到的数组的元素,
copyArr[1].age = 100
print("B:copyArr = \(copyArr)")
//B:copyArr = [debug:12, debug:100, debug:14]
print("B:perArr = \(perArr)")
//B:perArr = [debug:12, debug:13, debug:14]
//结果:原来数组的元素不会发生改变,两个输出结果里都是'debug:100'和‘debug:13’
//==============[case 2]=======================
//操作:新建一个元素,把元素添加到数组后再修改该元素
var testP = User(age:999)
copyArr.append(testP)
print("C:copyArr = \(copyArr)")
//C:copyArr = [debug:12, debug:100, debug:14, debug:999]
print("A:testP = \(testP)")
//A:testP = 999
testP.age = 888
print("D:copyArr = \(copyArr)")
//D:copyArr = [debug:12, debug:100, debug:14, debug:999]
//结果:数组的元素不会发生改变,输出结果里还是'debug:999';
}