4

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 Answer 1

3

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])
     }
}
2
  • Thank you for your answer, I tried to do it following your code. But then I get this error Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value in here appState.arrayInfos![index].
    – Tio
    Nov 23, 2020 at 11:08
  • Closed range includes 0 index, my fault - see updated with empty range as fix (now tested with Xcode 12.1)
    – Asperi
    Nov 23, 2020 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.