“Cannot assign to” error iterating through array of struct

前端 未结 3 1168
忘掉有多难
忘掉有多难 2021-01-17 08:01

I have an array of structs:

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

private var collectionData = [CalendarDate]()
         


        
3条回答
  •  不知归路
    2021-01-17 08:41

    As I understand it, the iterator

    for c in collectionData

    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..

    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 the iteration is the original value.

    Some of the other commentators suggested

    for (var c) in 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.

    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.

提交回复
热议问题