首页 > 解决方案 > 如何使用 SwiftUI 在 Xcode 中消除 foreach 循环的歧义

问题描述

我正在尝试在 Xcode 上使用 swiftUI 创建一个六边形网格。为了循环创建单个六边形,我使用了 foreach 循环。然而,我在创建一个创建一列六边形的函数时遇到了一个错误:

private func makeCol(C: Int, Bump:Int) -> some View {
        return ZStack {
            ForEach(-5...5, id: \.self) {Ynumber in                
                self.hexagon(
                    x: (ThreeRooted * self.L * Double(C)) + self.centerWidth,
                    y: (ThreeRooted * self.L * Double(Ynumber)) + self.centerHeight + (ThreeRootedOverTwo * self.L * Bump))
                    .stroke(Color.red, lineWidth: CGFloat(self.L/4.0))
            }
        }
    }

错误:编译器无法在合理时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式。

为了解决这个问题,我在单独的变量中提取了我的位置字段。但是,这给出了另一个错误:

private func makeCol(C: Int, Bump:Int) -> some View {
        return ZStack {
            ForEach(-5...5, id: \.self) {Ynumber in
                let xPlot = (ThreeRooted * self.L * Double(C)) + self.centerWidth
                let yPlot = (ThreeRooted * self.L * Double(Ynumber)) + self.centerHeight + (ThreeRootedOverTwo * self.L * Bump)

                self.hexagon(
                    x: xPlot,
                    y: yPlot)
                    .stroke(Color.red, lineWidth: CGFloat(self.L/4.0))
            }
        }
    } 

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

如何给这个循环一个明确的类型

标签: swiftxcodeswiftui

解决方案


如何给这个循环一个明确的类型?

ForEach(-5...5, id: \.self) { (Ynumber) -> _ExplicitType_ in
  ...
  return self.hexagon(
            ...
         )
}

推荐阅读