更改数组中struct的值 [英] Changing The value of struct in an array

查看:127
本文介绍了更改数组中struct的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将结构存储在数组中,在for循环中访问和更改结构的值.

I want to store structs inside an array, access and change the values of the struct in a for loop.

struct testing {
    var value:Int
}

var test1 = testing(value: 6 )

test1.value = 2
// this works with no issue

var test2 = testing(value: 12 )

var testings = [ test1, test2 ]

for test in testings{
    test.value = 3
// here I get the error:"Can not assign to 'value' in 'test'"
}

如果我将结构更改为class,那么它可以工作.谁能告诉我如何更改结构的值.

If I change the struct to class it works. Can anyone tell me how I can change the value of the struct.

推荐答案

除了@MikeS所说的以外,请记住结构是值类型.因此,在for循环中:

Besides what said by @MikeS, remember that structs are value types. So in the for loop:

for test in testings {

数组元素的

副本被分配给test变量.您对其所做的任何更改都将限制为test变量,而无需对数组元素进行任何实际更改.它适用于类,因为它们是引用类型,因此将 reference 而不是 value 复制到test变量.

a copy of an array element is assigned to the test variable. Any change you make on it is restricted to the test variable, without doing any actual change to the array elements. It works for classes because they are reference types, hence the reference and not the value is copied to the test variable.

执行此操作的正确方法是使用for按索引:

The proper way to do that is by using a for by index:

for index in 0..<testings.count {
    testings[index].value = 15
}

在这种情况下,您正在访问(并修改)实际的struct元素,而不是其副本.

in this case you are accessing (and modifying) the actual struct element and not a copy of it.

这篇关于更改数组中struct的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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