为什么 ForEach 在 SwiftUI 中初始化其子视图的次数是两倍?

Hol*_*ene 11 initialization swiftui swiftui-foreach swiftui-view

我遇到了 SwiftUI 的ForEach视图的奇怪行为。

我注意到 ForEach 总是根据其重复次数将其子视图初始化为应有的两倍。通常,当渲染视图时,它的 init 会被调用一次。但是,如果将视图放入 ForEach 中并循环 4 次,则子视图将被初始化 8 次,而不是 4 次。

这是我想要的行为还是我错过了什么?

您可以使用下面的简单代码对其进行测试。

测试环境:Xcode 14.0.1、iOS 16、模拟器 iPhone 13 Pro(带 iOS 16)

我很感激任何反馈!

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")
    }
}
Run Code Online (Sandbox Code Playgroud)