One strange behaviour: I have several objects and arrays:
for image in images {
for nextID in image.parts {
if nextID.number != 0 {
if let n = primaryLookUp[nextID.number] {
image.parts[0].newID = 0
nextID.newID = 0 // cannot assign!!!
}
}
}
nextID is simply going through the array of .parts. Does ist become a "let" assignment so I couldn't change anything later on? The
image.parts[0].newID = 0
is valid!
I believe this is the explanation for what you are seeing:
The value of a loop variable is immutable, just as if it had been assigned with
let.In your first loop,
imagesis an array of objects (defined by aclass). Since a class object is a reference type, you can alter the fields of the object. Only the loop variableimagein that case cannot be assigned.In your second loop,
image.partsis an array ofstructs. Since astructis a value type, the entirenextIDand its fields will be immutable within the loop.If you add
varto the second loop, you will be able to assign tonextID.newID:but, you are changing a copy of the
nextID(since structures copies are by value) and you are not changing thenextIDcontained in the originalimageobject.