Middle
What is the difference between copying an array and copying a struct in Swift?
sobes.tech AI
Answer from AI
Copied structure is a new independent instance. Changes in one structure do not affect the other.
Copying an array (Array) in Swift by default is "copy-on-write". This means that when a new reference to an array is created, the data is not duplicated until one of the copies is modified. Until then, both variables refer to the same elements in memory. When one copy is modified, a new independent data instance is created.
struct Point {
var x: Int
var y: Int
}
var p1 = Point(x: 1, y: 2)
var p2 = p1 // Copying the structure. p2 is a new instance
p2.x = 10 // Changing p2 does not affect p1
print("p1: \(p1.x), \(p1.y)") // Output: p1: 1, 2
print("p2: \(p2.x), \(p2.y)") // Output: p2: 10, 2
var array1 = [1, 2, 3]
var array2 = array1 // Copying on assignment
array2[0] = 10 // Actual data copying occurs
print("array1: \(array1)") // Output: array1: [1, 2, 3]
print("array2: \(array2)") // Output: array2: [10, 2, 3]
The difference lies in the fundamental behavior: structures are always copied by value, while arrays, being structures, implement "copy-on-write" optimization for more efficient memory management when there are multiple references.