János
János

Reputation: 35050

How to clone Swift generic array?

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.

Upvotes: 4

Views: 2376

Answers (3)

Mickael Belhassen
Mickael Belhassen

Reputation: 3342

@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
    }

}

Upvotes: 0

Sohayb Hassoun
Sohayb Hassoun

Reputation: 677

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

Upvotes: 2

NSSakly
NSSakly

Reputation: 209

Try this :

var myArray = [Double](count: 5, repeatedValue: 1.0)
NSLog("%@", myArray)
var copiedArray = myArray
NSLog("%@", copiedArray)

Upvotes: 2

Related Questions