Copy on write - forceUnwrap https://forceunwrap.com Lift your Swift skills & career to the next level Sat, 18 Mar 2023 07:25:36 +0000 en-US hourly 1 https://wordpress.org/?v=7.0 https://forceunwrap.com/wp-content/uploads/2023/03/cropped-ForceUnwrap-32x32.jpg Copy on write - forceUnwrap https://forceunwrap.com 32 32 Copy on write iOS developer interview question explained https://forceunwrap.com/copy-on-write-interview-question-explained/ https://forceunwrap.com/copy-on-write-interview-question-explained/#respond Wed, 15 Mar 2023 12:20:53 +0000 https://forceunwrap.com/?p=327
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.

The post Copy on write iOS developer interview question explained first appeared on forceUnwrap.

]]>
https://forceunwrap.com/copy-on-write-interview-question-explained/feed/ 0