Swiftui ForEach不能使用分支

Swiftui ForEach不能使用分支,swiftui,Swiftui,我正在使用Xcode 11.3.1和SwiftUI 这个代码工作正常 struct ContentView: View { var body: some View { VStack { ForEach(1...5, id: \.self) { index in Text("\(index) of coffee.") } } } } 但是下面的代码给出了一个错误 为什

我正在使用Xcode 11.3.1和SwiftUI

这个代码工作正常

struct ContentView: View {
    var body: some View {
        VStack {
            ForEach(1...5, id: \.self) { index in
                Text("\(index) of coffee.")
            }
        }
    }
}
但是下面的代码给出了一个错误

为什么?

错误消息是:

无法推断复杂的闭包返回类型;将显式类型添加到 消除歧义


因为视图生成器期望一种类型视图的一次返回,但条件不会生成不透明返回。要解决-只需在组中嵌入条件

ForEach(1...5, id: \.self) { index in
  Group {
    if index == 1 {
        Text("Cup of coffee.")
    } else {
        Text("\(index) cups of coffee")
    }
  }
}

解决方案是正确的,而不是解释。实际上,这个组有@inlinepublic init(@ViewBuilder content:()->content),这使它成为可能。对于每个人来说,除了满足。。。请更新您的答案,它可以帮助其他人正确理解它的工作原理。
ForEach(1...5, id: \.self) { index in
  Group {
    if index == 1 {
        Text("Cup of coffee.")
    } else {
        Text("\(index) cups of coffee")
    }
  }
}