Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() 
like image 200
Patrick Avatar asked Jan 07 '15 04:01

Patrick


People also ask

How do you duplicate an array?

If you want to copy the first few elements of an array or a full copy of an array, you can use Arrays. copyOf() method. Arrays. copyOfRange() is used to copy a specified range of an array.

Which method of an array creates a duplicate copy?

Use the clone method of the array. Clone methods create a new array of the same size.


1 Answers

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 = x let z = x.map { $0.copy() }  x[0] === y[0]   // true x[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.

like image 169
Nate Cook Avatar answered Sep 20 '22 14:09

Nate Cook