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 是值类型,因此在 for 循环中你正在处理一个副本.
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
}
斯威夫特 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 - 迭代结构对象时如何对其进行变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Swift - 迭代结构对象时如何对其进行变异
基础教程推荐
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
