[英]Why do I get error when I use ForEach in Xcode 11 Beta 5?
Error message: 错误信息:
Generic parameter 'ID' could not be inferred 无法推断通用参数“ ID”
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. 作为ForEach
的第一个参数传递的集合中的元素必须符合Identifiable
,或者必须使用其他初始化程序在元素上指定id的KeyPath
。 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
. models
数组不满足ForEach
初始化程序的要求,即,其元素不符合Identifiable
。 I can solve this in one of two ways: 我可以通过以下两种方式之一解决此问题:
1.) Extend MyModel
to conform to Identifiable
: 1.)扩展MyModel
使其符合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: 2)在ForEach
上使用便捷初始化程序,该初始化程序可让您指定标识符的KeyPath
:
var body: some View {
ForEach(models, id: \.name) { model in
Text(model.name)
}
}
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. @daltonclaybrook的回答很好,因为它解释了为什么会出现该错误并说明了创建自定义模型的正确方法。 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
: 但是,如果您正在寻找一种临时,快速且肮脏的解决方案,那么它对于Xcode 11.2.1和iOS 13.2中的String
数组适用于我:
ForEach(strings, id: \.self) { string in
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.