【问题标题】:Swift: Unable to infer complex closure return type; add explicit type to disambiguateSwift:无法推断复杂的闭包返回类型;添加显式类型以消除歧义
【发布时间】:2020-03-12 12:11:50
【问题描述】:
struct _9table: View {
    let digits: [Int] = [1,2,3,4,5,6,7,8,9]

    var body: some View {
        VStack{
            ForEach(self.digits, id: \.self) { first in
                ForEach(self.digits, id: \.self) { second in
                    if second > first {
                        Text("\(first)+\(second)=\(first+second)")
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • let digits = [1,2,3,4,5,6,7,8,9] Swift 将推断类型无需编写或短 let digits = (1...9)
  • Sh_Khan 谢谢你的回答

标签: swift swiftui


【解决方案1】:

根据错误,你需要帮助编译器找出返回类型,所以second -> Text? in而不是second in试试

struct _9table: View {
    let digits = (1...9)
    var body: some View {
        VStack{
            ForEach(self.digits, id: \.self) { first in
                ForEach(self.digits, id: \.self) { second -> Text? in
                    if second > first {
                        return Text("\(first)+\(second)=\(first+second)")
                    }
                    return nil
                }
            }
        }
    }
}

【讨论】:

  • 我明白了。在第二个 foreach 中它必须有一些回报。谢谢你的回答!
【解决方案2】:

之后再看其他答案。添加组很好

struct _9table: View {
let digits = (1...9)
var body: some View {
    VStack{
        ForEach(self.digits, id: \.self) { first in
            ForEach(self.digits, id: \.self) { second in
                Group{
                    if second > first {
                        return Text("\(first)+\(second)=\(first+second)")
                    }
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    相关资源
    最近更新 更多