如何创建一个空范围的foreach循环

时间:2020-06-01 11:51:55

标签: swift xcode swiftui

在我的应用中,我创建了一个父母名单。每个父级导航链接到子级子视图。当我添加一个新的父对象时,我的子视图会崩溃,因为还没有子对象。我认为问题与Range(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
    }
}

2 个答案:

答案 0 :(得分:1)

您可以添加if statement来检查是否有某些值,然后才进入ForEach循环或为孩子提供默认值:[]

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

答案 1 :(得分:0)

这是可行的方法

ForEach ((appState.parents[parentIndex].children ?? []).indices, id: \.self) { childIndex in
// ... other code here