How do I make a exact duplicate copy of an array? How do I make a exact duplicate copy of an array? arrays arrays

How do I make a exact duplicate copy of an array?


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 the NSCopying protocol, you can use the copy() method:

let x = [NSMutableArray(), NSMutableArray(), NSMutableArray()]let y = xlet z = x.map { $0.copy() }x[0] === y[0]   // truex[0] === z[0]   // false

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, its copy method just returns a reference to itself, so the test above would yield unexpected results.


Nate is correct. If you are working with primitive arrays all you need to do is assign duplicateArray to the originalArray.

For the sake of completeness, if you were working an NSArray object, you would do the following to do a full copy of an NSArray:

var originalArray = [1, 2, 3, 4] as NSArrayvar duplicateArray = NSArray(array:originalArray, copyItems: true)


There is a third option to Nate's answer:

let z = x.map { $0 }  // different array with same objects

* EDITED * edit starts here

Above is essentially the same as below and actually using the equality operator below will perform better since the array won't be copied unless it is changed (this is by design).

let z = x

Read more here: https://developer.apple.com/swift/blog/?id=10

* EDITED * edit ends here

adding or removing to this array won't affect the original array. However, changing any of the objects' any properties that the array holds would be seen in the original array. Because the objects in the array are not copies (assuming the array hold objects, not primitive numbers).