“无法分配给”迭代遍历struct数组的错误 [英] "Cannot assign to" error iterating through array of struct

查看:133
本文介绍了“无法分配给”迭代遍历struct数组的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构数组:

struct CalendarDate {
    var date: NSDate?
    var selected = false
}

private var collectionData = [CalendarDate]()

我只想填写这样的日期:

Which I simply populate with a date like this:

    for _ in 1...7 {
        collectionData.append(CalendarDate(date: NSDate(), selected: false))
    }

所以当你点击一个collectionView时,我只想循环遍历数据并将它们全部标记为False。

So when you tap on a collectionView, I simply want to loop through the data and mark them all as False.

    for c in collectionData {
        c.selected = false  ///ERROR: Cannot assign to 'selected' in 'c'
    }

为什么我会收到此错误?

Why do I get this error?

如果我这样做,它可以正常工作但我想要要知道上面我做错了什么:

If I do this, it works fine but I want to know what I did wrong above:

    for i in 0..<collectionData.count {
        collectionData[i].selected = false
    }


推荐答案

据我所知,迭代器

for collection中的c

返回 collectionData <中的项目副本/ code> - ( structs 是值类型,而不是引用类型,请参阅 http://www.objc.io/issue-16/swift-classes-vs-structs.html ),而迭代

returns copies of the items in collectionData - (structs are value types, not reference types, see http://www.objc.io/issue-16/swift-classes-vs-structs.html), whereas the iteration

for i in 0 ..< collectionData.count

访问实际值。如果我是正确的,那么分配给迭代器返回的 c 是没有意义的......它没有指向原始值,而

accesses the actual values. If I am right in that, it is pointless to assign to the c returned from the iterator... it does not "point" at the original value, whereas the

collectionData [i] .selected = false

in迭代原始值。

其他一些评论员建议

for collectionData <(var c) / code>

for (var c) in collectionData

虽然这允许你分配到 c ,但它仍然是一个副本,不是指向原始的指针,虽然您可以修改 c ,但 collectionData 仍然保持不变。

but although this allows you to assign to c, it is still a copy, not a pointer to the original, and though you can modify c, collectionData remains untouched.

答案是:A)使用最初记录的迭代或B)将数据类型更改为类,而不是结构。

The answer is either A) use the iteration as you originally noted or B) change the data type to a class, rather than a struct.

这篇关于“无法分配给”迭代遍历struct数组的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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