我有这个名为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 { ...
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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。