I have an array of tuples like so:
var tupleArray = [(userPhoto:UIImage?, student:PSStudent?, staff:PSStaff?)] = []
After adding values to that array, I would like to iterate through it and modify the userPhoto
value for each tuple as I go. Here is how I'm iterating:
for tuple in tupleArray {
let newImage = UIImage(systemName:"test")
tuple.userPhoto = newImage
}
However, when I try to set the value for userPhoto
inside the tuple, I'm shown the following:
Cannot assign to value: 'tuple' is a 'let' constant.
I'm sure there's some basic misunderstanding I have about variable tuples. Is what I'm attempting possible, or do I need to recreate the entire tupleArray inside a new variable and then assign that to the old one?
CodePudding user response:
The index variable tuple
is an immutable copy of the array item, even if it was mutable it won't modify the array.
You have to access the item in the array directly by index
for (index, _) in tupleArray.enumerated() {
let newImage = UIImage(systemName:"test")
tupleArray[index].userPhoto = newImage
}
or simpler and more efficient
let newImage = UIImage(systemName:"test")
for index in tupleArray.indices {
tupleArray[index].userPhoto = newImage
}
Side note: The issue is related to array, not to tuple. Anyway Apple recommends to prefer a custom struct over a tuple if the object is not temporary.