arrays – 更改数组中struct的值

前端之家收集整理的这篇文章主要介绍了arrays – 更改数组中struct的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想把结构体存储在数组中,在一个for循环中访问和改变结构体的值。
  1. struct testing {
  2. var value:Int
  3. }
  4.  
  5. var test1 = testing(value: 6 )
  6.  
  7. test1.value = 2
  8. // this works with no issue
  9.  
  10. var test2 = testing(value: 12 )
  11.  
  12. var testings = [ test1,test2 ]
  13.  
  14. for test in testings{
  15. test.value = 3
  16. // here I get the error:"Can not assign to 'value' in 'test'"
  17. }

如果我把结构改成类工作。任何人都可以告诉我如何可以改变结构的值。

除了@MikeS所说的,记住结构是值类型。所以在for循环中:
  1. for test in testings {

将数组元素的副本分配给测试变量。对它所做的任何更改都仅限于测试变量,而不对数组元素进行任何实际更改。它适用于类,因为它们是引用类型,因此引用而不是值复制到测试变量。

正确的方法是使用for by:

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

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

猜你在找的Swift相关文章