复制代码
a.append(4)
a[0] = 777
println(a[0])
// 777
println(b[0])
// 42
println(c[0])
// 42
设置数组是唯一的
b.unshare()
这时候如果再修改b的值,c的值也不会再受影响
b[0] = -105
println(a[0])
// 777
println(b[0])
// -105
println(c[0])
// 42
检查两个数组时候共用了相同的元素
if b === c {
println("b and c still share the same array elements.")
} else {
println("b and c now refer to two independent sets of array elements.")
}
// prints "b and c now refer to two independent sets of array elements."
也可以使用这个操作来判断两个子数组是否有共用的元素:
if b[0...1] === b[0...1] {
println("These two subarrays share the same elements.")
} else {
println("These two subarrays do not share the same elements.")
}
// prints "These two subarrays share the same elements."
强制数组拷贝
var names = ["Mohsen", "Hilary", "Justyn", "Amy", "Rich", "Graham", "Vic"]
var copiedNames = names.copy()
a.append(4)
a[0] = 777
println(a[0])
// 777
println(b[0])
// 42
println(c[0])
// 42
设置数组是唯一的
如果可以在对数组进行修改前,将它设置为唯一的就最好了。我们可以通过使用unshare方法来将数组自行拷贝出来,成为一个唯一的实体。
如果多个变量引用了同一个数组,可以使用unshare方法来完成一次“独立”
复制代码b.unshare()
这时候如果再修改b的值,c的值也不会再受影响
复制代码
b[0] = -105
println(a[0])
// 777
println(b[0])
// -105
println(c[0])
// 42
检查两个数组时候共用了相同的元素
使用实例相等操作符来判断两个数组是否共用了元素(===和!===)
下面这个例子演示的就是判断是否共用元素:
复制代码
if b === c {
println("b and c still share the same array elements.")
} else {
println("b and c now refer to two independent sets of array elements.")
}
// prints "b and c now refer to two independent sets of array elements."
也可以使用这个操作来判断两个子数组是否有共用的元素:
复制代码
if b[0...1] === b[0...1] {
println("These two subarrays share the same elements.")
} else {
println("These two subarrays do not share the same elements.")
}
// prints "These two subarrays share the same elements."
强制数组拷贝
通过调用数组的copy方法来完成强制拷贝。这个方法将会完整复制一个数组到新的数组中。
下面的例子中这个叫names的数组会被完整拷贝到copiedNames中去。
复制代码
var names = ["Mohsen", "Hilary", "Justyn", "Amy", "Rich", "Graham", "Vic"]
var copiedNames = names.copy()








