Sobes.tech
Junior

What happens if you make a copy of an array?

sobes.tech AI

Answer from AI

When copying an array in Swift, the default behavior is copy by value. This means that a new memory space is created, and all elements of the original array are placed there. Changes in the copy do not affect the original, and vice versa.

Example:

var originalArray = [1, 2, 3]
var copiedArray = originalArray // Copy by value occurs

copiedArray[0] = 100 // Only the copied array is changed

print(originalArray) // Output: [1, 2, 3] (original remains unchanged)
print(copiedArray)   // Output: [100, 2, 3]

It is important to note that this applies to arrays of structs, enums, and other value types. If the array contains reference types (e.g., class instances), then copying the array copies the references to these objects, not the objects themselves. In such cases, changes to an object's property via a reference in the copy will be visible in the original, and vice versa.

Example with a class:

class MyClass {
    var value: Int

    init(value: Int) {
        self.value = value
    }
}

var originalArrayOfObjects = [MyClass(value: 1), MyClass(value: 2)]
var copiedArrayOfObjects = originalArrayOfObjects // References to objects are copied

copiedArrayOfObjects[0].value = 100 // Change the property of the object via the reference in the copy

print(originalArrayOfObjects[0].value) // Output: 100 (changes are visible in the original)
print(copiedArrayOfObjects[0].value)   // Output: 100

If deep copying is required for arrays containing reference types, you need to implement a cloning mechanism for the elements themselves or use other approaches.