0
LazyVGrid(columns: columnGrid, spacing: 0) {
    if model.state == .two {
        ForEach(Array(model.cats.enumerated()), id: \.offset) { offset, cat in
            CatView(cat: cat)
                .frame(height: 50)
            }
        }
     } else {
         ForEach(Array(model.cats.enumerated()), id: \.offset) { offset, cat in
             CatView(cat: cat)
                 .frame(height: 50)
             }
         }
     }
}

When the model is in state "one", the else portion of this code block is executed, and all CatViews are updated properly. However, when the model state is changed to "two, the if portion of this executed. The ForEach line gets hit, and a breakpoint reveals that model.cats is valid. The problem is that the CatView() line is never executed in this case (it should be hit 10 times if there are 10 Cats for example). It's the exact same code as in the else block. What could be the reason the code inside the first ForEach block does not get executed?

soleil
  • 12,133
  • 33
  • 112
  • 183
  • This would benefit from a [mre]. Also, relying on the enumerated offset as an id is risky — it would be better to rely on a unique identifier for the model. – jnpdx Apr 03 '22 at 20:07
  • FWIW, I get the same results with ForEach(Array(zip(model.cats.indices, model.cats)), id: \.0) – soleil Apr 03 '22 at 20:17
  • B’it may be because you use the same id in if and in else – Ptit Xav Apr 03 '22 at 20:29
  • Indices are not reliable either (it’s the same thing as using enumerated). Try to use a truly unique identifier. – jnpdx Apr 03 '22 at 20:35
  • In practice, it's actually an array of characters. So, not sure how to give those unique identifiers. – soleil Apr 03 '22 at 20:48
  • I think the issue definitely has to do with the way ForEach is reusing things. So perhaps I should create a new question which is simply how to write a ForEach loop for an array of characters in a way that I have access to the index of each character. – soleil Apr 03 '22 at 21:01
  • Does this answer your question? [Same ForEach loop twice in one SwiftUI View](https://stackoverflow.com/questions/68141491/same-foreach-loop-twice-in-one-swiftui-view) – Ptit Xav Apr 03 '22 at 21:09
  • Whether it is this question or a new one, it would be helpful to include enough code to reproduce the issue. – jnpdx Apr 03 '22 at 21:15

0 Answers0