尝试从 API 数组创建页面选项卡视图时出现超出范围的索引错误

Getting the out of range index error when trying to make a Page Tab View from API array

这是我的模特:

class Api {
    func getRockets(completion: @escaping ([Rocket]) -> ()) {
        guard let url = URL(string: "https://api.spacexdata.com/v4/rockets") else { return }
        
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            do {
                let rockets = try JSONDecoder().decode([Rocket].self, from: data!)
                
                DispatchQueue.main.async {
                    completion(rockets)
                }
            } catch {
                print(error.localizedDescription)
            }
        }
        .resume()
    }
}

我尝试使用 API 数组中的元素创建 PageTabView,但我的应用程序因超出范围的索引错误而崩溃。

这是无法正常工作的视图:

struct TestTabViewView: View {
    @State var rockets: [Rocket] = [] //<-- The array of items from the API I use to make tabs
    
    var body: some View {
        TabView {
            ForEach(rockets) { rocket in
                Text(rocket.name)
            }
        }
        .onAppear {
            Api().getRockets { rockets in
                self.rockets = rockets
            }
        }
        .tabViewStyle(.page)
    }
}

struct TestTabViewView_Previews: PreviewProvider {
    static var previews: some View {
        TestTabViewView()
    }
}

如果将 TabView 放在 if-else 语句中,然后将此语句放在 NavigationViewGroup 中,然后调用 .onAppear外部容器的方法(例如,Group),一切都会正常工作,并且不会出现超出范围的索引错误。

struct TestTabViewView: View {
    @State var rockets: [Rocket] = []
    
    var body: some View {
        Group {
            if rockets.isEmpty {
                ProgressView()
            } else {
                TabView {
                    ForEach(rockets) { rocket in
                        Text(rocket.name)
                    }
                }
                .tabViewStyle(.page)
            }
        }
        .onAppear {
            Api().getRockets { rockets in
                self.rockets = rockets
            }
        }
    }
}