“Cannot assign to” error iterating through array of struct

前端 未结 3 1170
忘掉有多难
忘掉有多难 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:42

    If you are using structs they are copies in the array. So even changing them only changes the copy, not an actual object in the array.

    You have to make them a variable in the loop to be editable copy, and reassign them into the array right back.

    If they are classes and not structs, than you don't have to reassign part, just do the var thing.

    for (index, var c) in collectionData.enumerated() {
            c.selected = false
            collectionData[index] = c
        }
    

提交回复
热议问题