var firstArray = [1, 2, 3, 4, 5] // [1, 2, 3, 4, 5]
var secondArray = firstArray // [1, 2, 3, 4, 5]
print(firstArray == secondArray) // true
secondArray.append(6) // [1, 2, 3, 4, 5, 6]
print(firstArray.count) // 5
print(secondArray.count) // 6
print(firstArray == secondArray) // false
In Swift, when an array is assigned to another variable, a copy of the array is not created immediately. Instead, the new variable refers to the same memory location as the original array. This means that any changes made to the new variable are reflected in the original array as well.
However, Swift also uses a technique called Copy-On-Write (COW) to optimize memory usage. When a mutable operation is performed on an array (e.g. adding or removing an element), Swift checks whether the array has more than one reference to its memory location. If it does, Swift creates a new copy of the array before performing the mutation, so that the original array remains unchanged.
In the code provided, firstArray
is created with the values [1, 2, 3, 4, 5]
, and then secondArray
is assigned to firstArray
. Since secondArray
is not mutated at this point, it still refers to the same memory location as firstArray
.
The first print
statement outputs true
because firstArray
and secondArray
both contain the same values.
Next, the value 6
is appended to secondArray
. Since secondArray
now has more than one reference to its memory location, Swift creates a new copy of the array before appending the value. This means that firstArray
remains unchanged, and the print
statement that outputs 5
shows that firstArray
still has 5 elements.