Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

ios - "Cannot assign to" error iterating through array of struct

I have an array of structs:

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))
    }

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
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...