Middle
What is the difference between copying an array and a struct in Swift?
sobes.tech AI
Answer from AI
Copying an array in Swift creates a new independent copy of all its contents. Changes in the original array do not affect the copied one, and vice versa.
Copying a struct in Swift also creates a new copy of all its properties. If the struct contains nested reference types (e.g., classes), a reference to the object is copied, not the object itself. Changes within the reference type inside the copied struct are reflected in the original.
struct Point {
var x: Int
var y: Int
}
// Copying a struct
var point1 = Point(x: 10, y: 20)
var point2 = point1 // Copying the struct
point2.x = 30
print(point1.x) // Will print 10 (point1 remains unchanged)
class Container {
var value: Int
init(value: Int) {
self.value = value
}
}
struct HasReference {
var data: Container
}
// Copying a struct with a reference type
var ref1 = HasReference(data: Container(value: 100))
var ref2 = ref1 // Copying the struct
ref2.data.value = 200 // Changing the reference type inside the struct
print(ref1.data.value) // Will print 200 (change is reflected)
// Copying an array (by value)
var array1 = [1, 2, 3]
var array2 = array1 // Copying the array
array2[0] = 10
print(array1[0]) // Will print 1 (change in array2 did not affect array1)
// Copying an array containing reference types
var containers1 = [Container(value: 1), Container(value: 2)]
var containers2 = containers1 // Copying the array (references are copied)
containers2[0].value = 10 // Changing via reference in array2
print(containers1[0].value) // Will print 10 (change is reflected in array1)
| Feature | Array | Struct (without reference properties) | Struct (with reference properties) |
|---|---|---|---|
| Copy principle | By value (shallow copy) | By value | By value (references are copied) |
| Independence of copies | Independent by content | Independent by all properties | Independent by property-values, dependent on reference properties |
| Deep copying | Requires explicit implementation | Naturally | Requires explicit implementation for reference properties |