我有这个名为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 } }
我有一系列的餐:
var ordered = [Meal]()
我想复制该数组,然后对其中一个中的Meal实例进行一些更改而不更改第二个中的Meal实例,我将如何制作它的深层副本?
这个搜索结果对我没有帮助
How do I make a exact duplicate copy of an array?
由于ordered是一个swift数组,声明
原文链接:https://www.f2er.com/swift/320156.htmlvar orderedCopy = ordered
将有效地制作原始数组的副本.
但是,由于Meal是一个类,因此新数组将包含引用
与原来提到的同样的饭菜.
如果你想要复制膳食内容,那么在一个数组中改变一顿饭不会改变另一个阵列中的一餐,那么你必须将Meal定义为结构,而不是一个类:
struct Meal { ...
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.