Maric Vikike
Maric Vikike

Reputation: 247

Why do I get error when I use ForEach in Xcode 11 Beta 5?

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)")

}

Upvotes: 3

Views: 8409

Answers (2)

andrewz
andrewz

Reputation: 5220

The answer by @daltonclaybrook is great because it explains why you're getting that error and illustrates the correct approach of creating a custom model. But if you're looking for a temporary, quick and dirty solution this works for me in Xcode 11.2.1 and iOS 13.2 for an array of String:

ForEach(strings, id: \.self) { string in
   ...
}

Upvotes: 0

dalton_c
dalton_c

Reputation: 7171

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)
    }
}

Upvotes: 14

Related Questions