gpt4 book ai didi

swift - 快速复制对象数组

转载 作者:搜寻专家 更新时间:2023-10-30 22:01:20 25 4
gpt4 key购买 nike

我有一个名为 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 是一个,新数组将包含引用与原始食物中提到的相同食物。

如果你也想复制膳食内容,这样改变一个数组中的膳食不会改变另一个数组中的膳食,那么你必须将膳食定义为一个结构,而不是一个类:

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.

关于swift - 快速复制对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32357060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com