简体   繁体   中英

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.

Try this :

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

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM