How would I make an exact duplicate of an array?
I am having hard time finding information about duplicating an array in Swift.
I tried using .copy()
var originalArray = [1, 2, 3, 4]
var duplicateArray = originalArray.copy()
arrayscopyreferenceswift
How would I make an exact duplicate of an array?
I am having hard time finding information about duplicating an array in Swift.
I tried using .copy()
var originalArray = [1, 2, 3, 4]
var duplicateArray = originalArray.copy()
Best Answer
Arrays have full value semantics in Swift, so there's no need for anything fancy.
var duplicateArray = originalArray
is all you need.If the contents of your array are a reference type, then yes, this will only copy the pointers to your objects. To perform a deep copy of the contents, you would instead use
map
and perform a copy of each instance. For Foundation classes that conform to theNSCopying
protocol, you can use thecopy()
method:Note that there are pitfalls here that Swift's value semantics are working to protect you from—for example, since
NSArray
represents an immutable array, itscopy
method just returns a reference to itself, so the test above would yield unexpected results.