在Xcode 11 Beta 5中使用ForEach时为什么会出错?

Mar*_*ike 1 xcode swift ios13 swiftui xcode11

错误信息:

无法推断通用参数“ ID”

ForEach(0...self.workoutsViewModel.workoutRoutine[self.workoutIndex].routine[0].exercises.count - 1) { x in

    Text("\\(x)")

}
Run Code Online (Sandbox Code Playgroud)

dal*_*ook 5

您作为第一个参数传递的集合中的元素ForEach必须符合Identifiable,或者您必须使用其他初始化程序KeyPath在元素上指定id。例如,以下代码无法编译:

struct MyModel {
    let name: String
}

struct ContentView: View {
    let models: [MyModel]

    var body: some View {
        ForEach(models) { model in
            Text(model.name)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

models阵列不满足要求ForEach初始化,即,其元素不符合Identifiable。我可以通过以下两种方式之一解决此问题:

1.)扩展MyModel以符合Identifiable

extension MyModel: Identifiable {
    // assuming `name` is unique, it can be used as our identifier
    var id: String { name }
}
Run Code Online (Sandbox Code Playgroud)

2.)使用便捷初始化程序,ForEach该初始化程序允许您为KeyPath标识符指定a :

var body: some View {
    ForEach(models, id: \.name) { model in
        Text(model.name)
    }
}
Run Code Online (Sandbox Code Playgroud)