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

Solution 1:

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.

Solution 2:

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 NSArray

var duplicateArray = NSArray(array:originalArray, copyItems: true)

Solution 3:

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).

Solution 4:

For normal objects what can be done is to implement a protocol that supports copying, and make the object class implements this protocol like this:

protocol Copying {
    init(original: Self)
}

extension Copying {
    func copy() -> Self {
        return Self.init(original: self)
    }
}

And then the Array extension for cloning:

extension Array where Element: Copying {
    func clone() -> Array {
        var copiedArray = Array<Element>()
        for element in self {
            copiedArray.append(element.copy())
        }
        return copiedArray
    }
}

and that is pretty much it, to view code and a sample check this gist