I came across a weird behaviour of SwiftUI's ForEach view.
I've noticed that ForEach always initialize its child view twice as much as it should according to its repetition. Normally, when you render the view, its init is called once. But if you put the view inside ForEach and loop it 4 times, the child view is initialized 8 times instead of 4.
Is this a desired behavour or am I missing something?
You can test it using the simple code below.
tested on: Xcode 14.0.1, iOS 16, simulator iPhone 13 Pro (with iOS 16)
I am grateful for any feedback!
struct ContentView: View {
var body: some View {
VStack {
// Note that ForEach is looped 4 times!
ForEach(0..<4, id: \.self) { _ in
CustomView() // -> this view is initialized 8 times instead of 4.
}
}
}
}
struct CustomView: View {
// custom initializer with print to check how many times this view is initialized in log output
init() {
print("CustomView initialized")
}
var body: some View {
Text("Some Custom View")
}
}