To copy an array in Swift, you can use the Array initializer or the assignment operator.
In this example,
arr1
with elements.arr2
using the Array initializer Array(arr1)
.let arr1 = [1, 2, 3, 4, 5]
let arr2 = Array(arr1)
print("Array 1:", arr1)
print("Array 2 (copy of Array 1):", arr2)
Array 1: [1, 2, 3, 4, 5] Array 2 (copy of Array 1): [1, 2, 3, 4, 5]
In this example,
arr1
with elements.arr1
to arr2
directly using the assignment operator =
.arr2
.let arr1 = [1, 2, 3, 4, 5]
var arr2 = arr1
print("Array 1:", arr1)
print("Array 2 (copy of Array 1):", arr2)
Array 1: [1, 2, 3, 4, 5] Array 2 (copy of Array 1): [1, 2, 3, 4, 5]
In this tutorial, we learned How to Copy an Array in Swift language with well detailed examples.