如何在 SwiftUI 中的 ForEach 中分配变量?

gur*_*gui 5 foreach swift5 swiftui

是否可以在 SwiftUI 中设置变量,例如在 ForEach 中,如下所示:

\n\n
struct ContentView: View {\n    var test: Int\n\n    var body: some View {\n\n        List {\n            ForEach(1...5, id: \\.self) {\n                Text("\\($0)\xe2\x80\xa6")\n\n                test = $0 // how to realise this?\n            }\n        }\n\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我无法使其生效,我收到如下错误:

\n\n
Unable to infer complex closure return type; add explicit type to disambiguate\n
Run Code Online (Sandbox Code Playgroud)\n

Asp*_*eri 4

test您不能从内部的任何位置分配任何内容ContentView,因为它是结构体,因此self是不可变的,但您将能够执行如下操作:

\n\n
struct ContentView: View {\n//    var test: Int // cannot be assigned, because self is immutable\n\n    var body: some View {\n        List {\n            ForEach(1...5, id: \\.self) { (i) -> Text in\n                let test = i // calculate something intermediate\n                return Text("\\(test)\xe2\x80\xa6")\n            }\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n