【问题标题】:ForEach cannot use branchForEach 不能使用分支
【发布时间】:2020-03-22 06:42:56
【问题描述】:

我正在使用带有 SwiftUI 的 Xcode 11.3.1。

这段代码可以正常工作

struct ContentView: View {
    var body: some View {
        VStack {
            ForEach(1...5, id: \.self) { index in
                Text("\(index) of coffee.")
            }
        }
    }
}

但是下面的代码会报错。

为什么?

struct ContentView: View {
    var body: some View {
        VStack {
            ForEach(1...5, id: \.self) { index in
                if index == 1 {
                    Text("Cup of coffee.")
                } else {
                    Text("\(index) cups of coffee")
                }
            }
        }
    }
}

错误信息是:

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

【问题讨论】:

    标签: swiftui


    【解决方案1】:

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

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

    【讨论】:

    • 解决方法是对的,不是解释。实际上 Group 有 @inlinable public init(@ViewBuilder content: () -> Content) 这使得它成为可能。 ForEach 除了 Content ...请更新您的答案,它可以帮助其他人正确理解它的工作原理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多