Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deep copy for array of objects in swift

I have this class named Meal

class Meal {
    var name : String = ""
    var cnt : Int = 0
    var price : String = ""
    var img : String = ""
    var id : String = ""

    init(name:String , cnt : Int, price : String, img : String, id : String) {
        self.name = name
        self.cnt = cnt
        self.price = price
        self.img = img
        self.id = id
    }
}

and I have an array of Meal :

var ordered = [Meal]()

I want to duplicate that array and then do some changes to the Meal instances in one of them without changing the Meal instances in the second one, how would I make a deep copy of it?

This search result didn't help me How do I make a exact duplicate copy of an array?

like image 271
Mostafa Sultan Avatar asked Sep 02 '15 15:09

Mostafa Sultan


1 Answers

Since ordered is a swift array, the statement

 var orderedCopy = ordered

will effectively make a copy of the original array.

However, since Meal is a class, the new array will contain references to the same meals referred in the original one.

If you want to copy the meals content too, so that changing a meal in one array will not change a meal in the other array, then you must define Meal as a struct, not as a class:

struct Meal { 
  ...

From the Apple book:

Use struct to create a structure. Structures support many of the same behaviors as classes, including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference.

like image 89
Mario Zannone Avatar answered Nov 14 '22 10:11

Mario Zannone