【问题标题】:How to assign a variable in e.g. a ForEach in SwiftUI?如何分配变量,例如SwiftUI 中的 ForEach?
【发布时间】:2020-06-23 09:12:20
【问题描述】:

是否可以在 SwiftUI 中设置变量,例如在这样的 ForEach 中:

struct ContentView: View {
    var test: Int

    var body: some View {

        List {
            ForEach(1...5, id: \.self) {
                Text("\($0)…")

                test = $0 // how to realise this?
            }
        }

    }
}

我无法实现它,我收到如下错误:

Unable to infer complex closure return type; add explicit type to disambiguate

【问题讨论】:

  • 如果你需要这样做,你做错了什么。您应该问自己的问题是“为什么我需要分配给test?”
  • 在循环中我会有一些部分。而且我需要动态地对项目进行分组,因此我需要始终检查上一个。物品。因此我想把它存放在某个地方。

标签: foreach swiftui swift5


【解决方案1】:

你不能从ContentView 的任何地方内部分配任何东西给test,因为它是结构体,所以self 是不可变的,但是你可以在以下:

struct ContentView: View {
//    var test: Int // cannot be assigned, because self is immutable

    var body: some View {
        List {
            ForEach(1...5, id: \.self) { (i) -> Text in
                let test = i // calculate something intermediate
                return Text("\(test)…")
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多