arrays – 更改数组中struct的值

arrays – 更改数组中struct的值,第1张

概述我想把结构体存储在数组中,在一个for循环中访问和改变结构体的值。 struct testing { var value:Int}var test1 = testing(value: 6 )test1.value = 2// this works with no issuevar test2 = testing(value: 12 )var testings = [ t 我想把结构体存储在数组中,在一个for循环中访问和改变结构体的值。
struct testing {    var value:Int}var test1 = testing(value: 6 )test1.value = 2// this works with no issuevar 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'"}

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

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

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

正确的方法是使用for by:

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

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

总结

以上是内存溢出为你收集整理的arrays – 更改数组中struct的值全部内容,希望文章能够帮你解决arrays – 更改数组中struct的值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1055963.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存