Swift - 迭代结构对象时如何对其进行变异

2024-04-15移动开发问题
7

本文介绍了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 - 迭代结构对象时如何对其进行变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

突出显示朗读文本(在 iPhone 的故事书类型应用程序中)
Highlight Read-Along Text (in a storybook type app for iPhone)(突出显示朗读文本(在 iPhone 的故事书类型应用程序中))...
2024-08-12 移动开发问题
9

从 Documents 目录存储和读取文件 iOS 5
Storing and reading files from Documents directory iOS 5(从 Documents 目录存储和读取文件 iOS 5)...
2024-08-12 移动开发问题
9

如何在使用 cocos2d 的 iphone 应用程序中使用 MYSQL 数据库连接?
How can i use MYSQL database connection in iphone application useing cocos2d?(如何在使用 cocos2d 的 iphone 应用程序中使用 MYSQL 数据库连接?)...
2024-08-12 移动开发问题
5

在 cocos2d 中平滑拖动一个 Sprite - iPhone
Smoothly drag a Sprite in cocos2d - iPhone(在 cocos2d 中平滑拖动一个 Sprite - iPhone)...
2024-08-12 移动开发问题
10

RPG 游戏循环和类结构(cocos2D for iPhone)
RPG Game loop and class structure (cocos2D for iPhone)(RPG 游戏循环和类结构(cocos2D for iPhone))...
2024-08-12 移动开发问题
6