快速复制对象数组的深层副本 [英] deep copy for array of objects in swift
问题描述
我有一个名为Meal的课程
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
}
}
并且我有一组膳食:
var ordered = [Meal]()
我想复制该数组,然后对其中之一的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?
推荐答案
由于已排序
是一个快速数组,语句
Since ordered
is a swift array, the statement
var orderedCopy = ordered
将有效地复制原始数组。
will effectively make a copy of the original array.
但是,由于Meal是 class ,新数组将包含对原始餐点所引用的相同餐点的引用
。
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 {
...
从 Apple书:
使用结构创建结构。结构支持许多与类相同的行为,包括方法和初始化程序。结构和类之间最重要的区别之一是,结构在代码中传递时总是被复制,而类是通过引用传递的。
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.
这篇关于快速复制对象数组的深层副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!