Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a deep copy of a swift array of class objects

Tags:

ios

swift

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.

like image 563
Wingzero Avatar asked Dec 24 '15 02:12

Wingzero


1 Answers

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.

like image 61
Duncan C Avatar answered Sep 22 '22 18:09

Duncan C