Swift - 如何在迭代结构对象时对其进行变异 [英] Swift - How to mutate a struct object when iterating over it

查看:19
本文介绍了Swift - 如何在迭代结构对象时对其进行变异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然不确定结构体复制或引用的规则.

我想在从数组迭代结构对象的同时对其进行变异:例如在这种情况下,我想更改背景颜色但是编译器在对我大喊大叫

结构选项{var backgroundColor = UIColor.blackColor()}var arrayOfMyStruct = [MyStruct]...对于 arrayOfMyStruct { 中的 objobj.backgroundColor = UIColor.redColor()//!得到一个错误}

解决方案

struct 是值类型,因此在 for 循环中您正在处理一个副本.

就像测试一样,你可以试试这个:

斯威夫特 3:

结构选项{var backgroundColor = UIColor.black}var arrayOfMyStruct = [选项]()for (index, _) in arrayOfMyStruct.enumerated() {arrayOfMyStruct[index].backgroundColor = UIColor.red}

斯威夫特 2:

结构选项{var backgroundColor = UIColor.blackColor()}var arrayOfMyStruct = [选项]()for (index, _) in enumerate(arrayOfMyStruct) {arrayOfMyStruct[index].backgroundColor = UIColor.redColor()}

这里只是枚举索引,直接访问数组中存储的值.

希望这会有所帮助.

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 are value types, thus in the for loop you are dealing with a copy.

Just as a test you might try this:

Swift 3:

struct Options {
   var backgroundColor = UIColor.black
}

var arrayOfMyStruct = [Options]()

for (index, _) in arrayOfMyStruct.enumerated() {
   arrayOfMyStruct[index].backgroundColor = UIColor.red
}

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.

Hope this helps.

这篇关于Swift - 如何在迭代结构对象时对其进行变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆