swift中对象数组的深层复制

我有这个名为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数组,声明
var orderedcopy = ordered

将有效地制作原始数组的副本.

但是,由于Meal是一个类,因此新数组将包含引用
与原来提到的同样的饭菜.

如果你想要复制膳食内容,那么在一个数组中改变一顿饭不会改变另一个阵列中的一餐,那么你必须将Meal定义为结构,而不是一个类:

struct Meal { 
  ...

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.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...