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

问题描述 投票:1回答:2
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)")
                    }
                }
            }
        }
    }
}
swift swiftui
2个回答
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
                }
            }
        }
    }
}

0
投票

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

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)")
                    }
                }
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.