How to set a default value as Range<Int> when I use a ForEach method?

Viewed 572

I'm currently developing an application using SwiftUI.

I want to know how to set a default value of count as Range<Int> when I use a ForEach method.

because of using an array object created by an async method, when I use ForEach method I have to set a default value.

If I set the default value just 0, I get an error below:

Cannot convert value of type 'Int' to expected argument type 'Range<Int>'

How could I set a value as Range<Int> then?


Here are the codes:

*I want to set 0 as the default value

ContentView.swift

...
@EnvironmentObject var appState: AppState

ForEach(0..<appState.arrayInfos?.count ?? 0 ,id: \.self){ index in
     VStack{
         InfoRow(no: index,info:appState.arrayInfos![index] )
     }
}
...

AppState.swift

class AppState: ObservableObject {

    @Published var arrayInfos:[ArrayInfos]?

}

...
let task = session.dataTask(with: urlRequest) {
        (data, response, error) in
        
        DispatchQueue.main.async {
            do{ self.arrayInfos = try JSONDecoder().decode([ArrayInfos].self, from: responseData)
            }catch{
                print("Error: did not decode")
                return
            }
        }
    }
    task.resume()
...

Xcode: Version 12.0.1

1 Answers

You need to use dynamic variant of ForEach, otherwise it will not be updated when data appeared

ForEach(appState.arrayInfos?.indices ?? 0..<0, id: \.self) { index in
     VStack {
         InfoRow(no: index, info: appState.arrayInfos![index])
     }
}
Related