0

In my app I create a list of parents. Each Parent navigationlinks to a subview of children. When I add a new parent, my subview crashes because there are no children yet. I think the issue is related to Range(0...0) what is still a range that loops once. How can I have an empty loop if indices is nil?

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
    }
}
PhilHarmonie
  • 415
  • 1
  • 5
  • 16

2 Answers2

0

You can add an if statement to check if there are some values and only then enter a ForEach loop or provide a default value for your children: [].

if appState.parents[parentIndex].children? != nil {
    ForEach(appState.parents[parentIndex].children!.indices, id: \.self) {...}
}
pawello2222
  • 34,912
  • 15
  • 99
  • 151
0

Here is possible approach

ForEach ((appState.parents[parentIndex].children ?? []).indices, id: \.self) { childIndex in
// ... other code here
Asperi
  • 173,274
  • 14
  • 284
  • 455