[英]Copy a variable with value in Swift
I have a variable declared in this way我有一个以这种方式声明的变量
var model: cellModelCollection<AnyObject, collectionViewCell>
I want to create another variable modelCopy with the same values as model but if I delete an item from modelCopy I don't want it to be deleted from model .我想创建另一个与model具有相同值的变量modelCopy但如果我从modelCopy 中删除一个项目,我不希望它从model 中删除。
let modelCopy = model
don't work. let modelCopy = model
不起作用。
I also tried to create a struct s我也尝试创建一个 struct s
a.model = self.model
b.model = self.model
//delete an item from a.model
print (a.model.count) // 32
print (b.model.count) // 32 element also deleted from b
Your cellModelCollection
should be of type struct , not class .您的cellModelCollection
应该是struct类型,而不是class 。 Structures are always copied when they are passed around in your code, and do not use reference counting.结构在您的代码中传递时总是被复制,并且不使用引用计数。 Check example below in storyboard.在故事板中查看下面的示例。 You will see that print will produce different results.您将看到打印将产生不同的结果。
struct Model {
var arg = [0, 1, 2]
}
struct Struct {
var model: Model?
}
var myStruct1 = Struct()
var myStruct2 = Struct()
var myModel = Model()
myStruct1.model = myModel
myModel.arg.removeLast()
myStruct2.model = myModel
print(myStruct1.model!.arg)
print(myStruct2.model!.arg)
This gives result:这给出了结果:
[0, 1, 2]
[0, 1]
BUT if you change struct Model
to class Model
then result of printing will be the same:但是,如果您将struct Model
更改为class Model
则打印结果将相同:
[0, 1]
[0, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.