Swift 如何创建具有空范围的foreach循环

Swift 如何创建具有空范围的foreach循环,swift,xcode,swiftui,Swift,Xcode,Swiftui,在我的应用程序中,我创建了一个家长列表。每个父导航链接到子视图。当我添加新的父视图时,我的子视图崩溃,因为还没有子视图。我认为这个问题与范围(0…0)有关,它仍然是一个循环一次的范围。如果索引为零,我怎么可能有一个空循环 ForEach (appState.parents[parentIndex].children?.indices ?? Range(0...0), id: \.self) { childIndex in NavigationLink (destination: Pupp

在我的应用程序中,我创建了一个家长列表。每个父导航链接到子视图。当我添加新的父视图时,我的子视图崩溃,因为还没有子视图。我认为这个问题与范围(0…0)有关,它仍然是一个循环一次的范围。如果索引为零,我怎么可能有一个空循环

ForEach (appState.parents[parentIndex].children?.indices ?? Range(0...0), id: \.self) { childIndex in
    NavigationLink (destination: PuppetsView(parentIndex: self.parentIndex, childIndex: childIndex).environmentObject(self.appState)) {
        Text(self.appState.parents[self.parentIndex].children![childIndex].name) // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
    }
}

您可以添加一个
if语句
来检查是否有一些值,然后才输入一个
ForEach
循环或为您的孩子提供一个默认值:
[]

if appState.parents[parentIndex].children? != nil {
    ForEach(appState.parents[parentIndex].children!.indices, id: \.self) {...}
}

这是可能的方法

ForEach ((appState.parents[parentIndex].children ?? []).indices, id: \.self) { childIndex in
// ... other code here
空范围应为
0。。