0

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
    }
    
}
Jmcg
  • 239
  • 2
  • 9

1 Answers1

0

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)")
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • That works perfectly, but in my real app, I call a function in onAppear after fetchdata, to do some processing using testViewModel. If I put in your !testViewModel.test.isEmpty the code in the function never gets run. – Jmcg Sep 30 '20 at 15:39
  • So it does appear I am trying to use the object before it is available – Jmcg Sep 30 '20 at 15:41