我这里有这个 Swift 代码:
struct chapter: View {
var body: some View {
Form {
ForEach(1..<18) { _ in
NavigationLink(destination: chapterrun()) {
Text("Chapter \($0)")
}
}
}
.navigationTitle("App")
}
}
Run Code Online (Sandbox Code Playgroud)
但它给出了错误:
Contextual closure type '() -> Text' expects 0 arguments, but 1 was used in closure body
我该如何解决?
您有两个闭包,因此第一个闭包中的 $0 (即使它是正确的,但_ in您只需忽略它)在第二个闭包中不可用。
解决方法是显式使用参数,例如
ForEach(1..<18) { index in // << here !!
NavigationLink(destination: chapterrun()) {
Text("Chapter \(index)") // << here !!
}
}
Run Code Online (Sandbox Code Playgroud)