Error message:
Generic parameter 'ID' could not be inferred
ForEach(0...self.workoutsViewModel.workoutRoutine[self.workoutIndex].routine[0].exercises.count - 1) { x in
Text("\\(x)")
}
The elements in the collection you pass as the first argument of ForEach
must conform to Identifiable
, or you must use a different initializer to specify the KeyPath
of the id on your elements. For example, the following code does not compile:
struct MyModel {
let name: String
}
struct ContentView: View {
let models: [MyModel]
var body: some View {
ForEach(models) { model in
Text(model.name)
}
}
}
The models
array does not satisfy the requirements of the ForEach
initializer, namely, its elements do not conform to Identifiable
. I can solve this in one of two ways:
1.) Extend MyModel
to conform to Identifiable
:
extension MyModel: Identifiable {
// assuming `name` is unique, it can be used as our identifier
var id: String { name }
}
2.) Use the convenience initializer on ForEach
that allows you to specify a KeyPath
to your identifier:
var body: some View {
ForEach(models, id: \.name) { model in
Text(model.name)
}
}