[ad_1]
I’ve a difficulty when use ForEach in one other ForEach(nested ForEach),
Think about we’ve a customized view like this:
struct XCom<Content material> : View the place Content material : View {
var content material:Content material
var title: String
init(title: String, @ViewBuilder _ content material: @escaping () -> Content material) {
self.title = title
self.content material = content material()
print(title)
}
var physique: some View {
VStack {
content material
}
}
}
First instance, we’ve one ForEach and use the XCom.
func test1() -> some View {
ForEach(0...1, id: .self) { index in
XCom(title: "First view (index) created") {
XCom(title: "First internal view (index) created") {}
}
XCom(title: "Second view (index) created") {
XCom(title: "Second internal view (index) created") {}
}
}
}
Debug outcome:
First internal view 0 created
First view 0 created
Second internal view 0 created
Second view 0 created
First internal view 1 created
First view 1 created
Second internal view 1 created
Second view 1 created
However, once I use nested ForEach, the ForEach iteration algorithm change.
func test2() -> some View {
ForEach(0...1, id: .self) { index in
XCom(title: "First view (index) created") {
ForEach(0...1, id: .self) { index2 in
XCom(title: "First internal view (index) (index2) created") {}
}
}
XCom(title: "Second view (index) created") {
ForEach(0...1, id: .self) { index2 in
XCom(title: "Second internal view (index) (index2) created") {}
}
}
}
}
Debug outcome:
First view 0 created
Second view 0 created
First view 1 created
Second view 1 created
First internal view 0 0 created
First internal view 0 1 created
Second internal view 0 0 created
Second internal view 0 1 created
First internal view 1 0 created
First internal view 1 1 created
Second internal view 1 0 created
Second internal view 1 1 created
within the first instance, the ForEach iteration algorithm begins from the internal view to the father or mother view, however within the 2nd instance first, the father or mother view was created then the internal view was created.
the anticipated output for the 2nd instance:
First internal view 0 0 created
First internal view 0 1 created
First view 0 created
Second internal view 0 0 created
Second internal view 0 1 created
Second view 0 created
First internal view 1 0 created
First internal view 1 1 created
First view 1 created
Second internal view 1 0 created
Second internal view 1 1 created
Second view 1 created
[ad_2]
