So I know that swift array is implemented as struct, and it will do automatically copy by itself.
I have write my class MyClass
and I have implemented copyWithZone
to make copy of it
However, my swift array contains my MyClass
objects, like:
var array = [MyClass]()
when I wan to make a copy of that array like
var anotherArray = array
It still does not call MyClassObject.copyWithZone
, and later if I change the object property in array
, anotherArray
will also reflect the change.
How can I make a copy of that without writing a for loop to iterate every object?
It's not duplicated as deep copy for array of objects in swift because I cannot use struct to rewrite my class.
As a simple statement, you could use code like this:
var copiedArray = array.map{$0.copy()}
Note that the term "deepCopy" is a little misleading for what you're talking about. What if the array is heterogeneous and contains other containers like arrays, dictionaries, sets, and other custom container and "leaf" objects? What you should really do is to create a protocol DeepCopiable and make it a requirement that any object that conforms to DeepCopiable require that any child objects also conform to the DeepCopiable protocol, and write the deepCopy() method to recursively call deepCopy() on all child objects. That way you wind up with a deep copy that works at any arbitrary depth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With