Using a ForEach loop breaks my data binding to an object in an array. I can create my view using the index of zero - array[0] - and it responds to the databinding appropriately. If I wrap it with a ForEach but do not change the index of zero to an iterator - array[0] NOT array[index], it still creates the view, but now the data binding does not work. Same exact code, just wrapped in a ForEach loop that should only loop once (the array only has one object inside).
// Does data bind correctly - UI is updated
if(self.noise.twoControlEffects[0].isDisplayed){
TwoControlTemplate(title: "Low Pass Filter",
isBypassed: self.$noise.twoControlEffects[0].isBypassed,
knobModel1: self.$noise.twoControlEffects[0].control1,
knobModel2: self.$noise.twoControlEffects[0].control2)
}
// Does not update UI
ForEach(noise.twoControlEffects.indices){ index in
if(self.noise.twoControlEffects[0].isDisplayed){
TwoControlTemplate(title: "Low Pass Filter",
isBypassed: self.$noise.twoControlEffects[0].isBypassed,
knobModel1: self.$noise.twoControlEffects[0].control1,
knobModel2: self.$noise.twoControlEffects[0].control2)
}
}
I tried it with array[index] as well, but then did the above once it was not working.
// Does not update UI
ForEach(noise.twoControlEffects.indices){ index in
if(self.noise.twoControlEffects[index].isDisplayed){
Spacer()
TwoControlTemplate(title: "Low Pass Filter",
isBypassed: self.$noise.twoControlEffects[index].isBypassed,
knobModel1: self.$noise.twoControlEffects[index].control1,
knobModel2: self.$noise.twoControlEffects[index].control2)
}
}
What does the ForEach loop do that breaks databinding? How can I create and update views using an array of objects?
The ForEach View cannot not work with indicies for dynamic data, it requires identifiers which is why we supply it with an array of Identifiable data.
This is so that it can calculate inserts, moves and deletions which obviously is impossible with an array of indicies which will in the case of moving 5 items around the indices will still be 0-4.