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

ArraysSwiftReferenceCopy

Arrays Problem Overview


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

Arrays Solutions


Solution 1 - Arrays

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 - Arrays

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 - Arrays

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 - Arrays

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

Solution 5 - Arrays

If you want to copy the items of an array of some class object. Then you can follow the below code without using NSCopying protocol but you need to have an init method which should take all the parameters that are required for your object. Here is the code for an example to test on playground.

class ABC {
    
    var a = 0
    func myCopy() -> ABC {
        
        return ABC(value: self.a)
    }
    
    init(value: Int) {
        
        self.a = value
    }
}

var arrayA: [ABC] = [ABC(value: 1)]
var arrayB: [ABC] = arrayA.map { $0.myCopy() }

arrayB.first?.a = 2
print(arrayA.first?.a)//Prints 1
print(arrayB.first?.a)//Prints 2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrickView Question on Stackoverflow
Solution 1 - ArraysNate CookView Answer on Stackoverflow
Solution 2 - Arraysapplejack42View Answer on Stackoverflow
Solution 3 - ArraysoyalhiView Answer on Stackoverflow
Solution 4 - ArraysSohayb HassounView Answer on Stackoverflow
Solution 5 - ArraysNoman HaroonView Answer on Stackoverflow