4

I need to deep copy a Swift generic array. I can do it one by one in a for loop, but there might be a more compact solution.

3 Answers 3

2

Try this :

var myArray = [Double](count: 5, repeatedValue: 1.0)
NSLog("%@", myArray)
var copiedArray = myArray
NSLog("%@", copiedArray)
Sign up to request clarification or add additional context in comments.

5 Comments

yes, meantime I noticed that assigning with = makes a true copy, not only the reference is set
This is actually a shallow copy. Work for Double as they are value types, but what about class types like NSString?
Just initialise your array as strings : var threeDoubles = [String](count: 3, repeatedValue: "myString") for any other type initialise it with your type of object
copiedArray is a shallow copy of myArray in swift.
This is indeed a shallow copy
2

For deep copying, 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

Comments

0

@Sohayb Hassoun approved function to clone array:

extension Array where Element: Cloneable {

    func clone() -> Array {
        let copiedArray: Array<Element> = self.compactMap { $0.cloned() }
        return copiedArray
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.