Swift - 如何在迭代结构对象时改变它 [英] Swift - How to mutate a struct object when iterating over it
本文介绍了Swift - 如何在迭代结构对象时改变它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我仍然不确定结构复制或引用的规则。
I am still not sure about the rules of struct copy or reference.
我想要改变一个结构体对象,同时从一个数组进行迭代:
例如在这种情况下,我想改变背景颜色
,但编译器对我大喊大叫。
I want to mutate a struct object while iterating on it from an array: For instance in this case I would like to change the background color but the compiler is yelling at me
struct Options {
var backgroundColor = UIColor.blackColor()
}
var arrayOfMyStruct = [MyStruct]
...
for obj in arrayOfMyStruct {
obj.backgroundColor = UIColor.redColor() // ! get an error
}
推荐答案
struct
是值类型,因此在为
循环你正在处理一个副本。
struct
are value types, thus in the for
loop you are dealing with a copy.
正如测试你可以尝试这样:
Just as a test you might try this:
struct Options {
var backgroundColor = UIColor.black
}
var arrayOfMyStruct = [Options]()
for (index, _) in arrayOfMyStruct.enumerated() {
arrayOfMyStruct[index].backgroundColor = UIColor.red
}
Swift 2:
Swift 2:
struct Options {
var backgroundColor = UIColor.blackColor()
}
var arrayOfMyStruct = [Options]()
for (index, _) in enumerate(arrayOfMyStruct) {
arrayOfMyStruct[index].backgroundColor = UIColor.redColor()
}
这里你只是枚举索引,
Here you just enumerate the index, and access directly the value stored in the array.
希望这有助于。
这篇关于Swift - 如何在迭代结构对象时改变它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文