SwiftUI @ObservedObect View Model Index out of Range

94 views Asked by At

In Swift I have a viewModel which connects to FireStore and when I call its function fetchData it returns a number of documents successfully. But when I try to reference a document using an index I get an Out of Range error.

In this example the count of documents comes back as 1 so I cannot see why the next Text statement doesn't work. Could it be a timing issue? Meaning, is the document actually available at that moment.

@ObservedObject var testViewModel = GetTestViewModel()

var body: some View {
    
    VStack {
        Text("Number of tests = \(testViewModel.test.count)") // Returns 1
        Text("Test Level = \(testViewModel.test[0].level)")
        // Allways crashes with Fatal error: Index out of range
        
    }
            .onAppear() {
        // This should and does return one record
        testViewModel.fetchdata(testId: "4Yv7iT2BjHCKNzr4umpG")
        LoadNewTest()
        
    }
}
func LoadNewTest() {
    print("Load Test")
    if !testViewModel.test.isEmpty {
        print("Number of tests = \(testViewModel.test.count)") // Never prints
    }
    
}
1

There are 1 answers

2
Asperi On

You might not see first request to body when count yet zero, so it is better to added condition explicitly, like

VStack {
    Text("Number of tests = \(testViewModel.test.count)") // Returns 1

    if !testViewModel.test.isEmpty {
       Text("Test Level = \(testViewModel.test[0].level)")
    }
}