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
Try this :
var myArray = [Double](count: 5, repeatedValue: 1.0)
NSLog("%@", myArray)
var copiedArray = myArray
NSLog("%@", copiedArray)
5 Comments
János
yes, meantime I noticed that assigning with
= makes a true copy, not only the reference is setKirsteins
This is actually a shallow copy. Work for
Double as they are value types, but what about class types like NSString?NSSakly
Just initialise your array as strings : var threeDoubles = [String](count: 3, repeatedValue: "myString") for any other type initialise it with your type of object
Dilip Lilaramani
copiedArray is a shallow copy of myArray in swift.
Ferschae Naej
This is indeed a shallow copy
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