递归 SwiftUI 视图

Recursive SwiftUI views

出于某种原因,我无法显示在 ForEach 循环中调用自身的 SwiftUI 视图。应用程序在尝试显示此视图时挂起然后崩溃:

struct LoopView: View {
    let loop: Loop

    var body: some View {
        HStack {
            Text(String(loop.multiplier))
                .font(.title)
            Text("x")
            VStack {
                // ### THE PROBLEM IS HERE ###
                if let loops = loop.loops {
                    ForEach(loops, id: \.id) { innerLoop in
//                        Text(String(innerLoop.multiplier)) // << This works
                        LoopView(loop: innerLoop) // << This causes the system to hang
                    }
                } else {
                    // This stuff here is fine
                    if let components = loop.components {
                        ForEach(components, id: \.id) { component in
                            ComponentView(component: component)
                        }
                    }
                }
            }
        }
    }
}

struct LoopView_Previews: PreviewProvider {
    static let moc = DataController.preview.container.viewContext

    static var previews: some View {
        let outterLoop = Loop(context: moc)
        outterLoop.id = UUID()
        outterLoop.multiplier = 5
        outterLoop.addToInternalLoops(DataController.exampleLoop())

        // vvv Does not change outcome if commented out vvv
        outterLoop.addToInternalLoops(DataController.exampleLoop())

        return LoopView(loop: outterLoop)
    }
}

根据评论,我可以很好地访问循环项的属性,这意味着循环没有问题,可以访问元素。但是,我无法递归使用 loopinnerLoop 不包含 loop 意味着它将在仅深入一层后停止递归。

我正在使用 Xcode 13.2.1。感谢您的帮助!

进行了更多调试,发现错误来自我的自引用一对多实体需要对自身的反向引用。有关详细信息,请参阅 this post