0

如何将捕获列表添加到 SwiftUI .sheet(content: ) 闭包?

我在 SwiftUI 和内容中有一张工作表:closure 我检查一个可选的值以确定要显示的视图。第一次运行时,即使我事先设置了它,它的值也总是为零。我提交了一份错误报告,Apple 说如果我在闭包的捕获列表中引用该变量,那么它将按预期工作。我是 SwiftUI 的新手,无法弄清楚这样做的正确语法。语法是什么?

struct ContentView: View {

   @State var presentButtonTwoDetail: Bool = false
   
   @State var seletedIndex: Int? = nil

   var body: some View {
            Text("Hello")
            .sheet(isPresented: $presentButtonTwoDetail) {
                selectedIndex = nil
            } content: {
                {
                    [selectedIndex] // This syntax won't compile
                    () -> View in
                    if let theIndex = selectedIndex {
                        DetailView(selectedIndex: theIndex)
                    } else {
                        // This gets called on the first run only even when the `selectedIndex` is not nil.
                        DetailView(selectedIndex: 0)
                    }
                }
            }
    }
}
4

1 回答 1

1

这编译。

struct ContentView: View {
    
    @State var presentButtonTwoDetail: Bool = false
    
    @State var selectedIndex: Int? = nil
    
    var body: some View {
        Text("Hello")
            .sheet(isPresented: $presentButtonTwoDetail) {
                selectedIndex = nil
            } content: { [selectedIndex] in
                if let theIndex = selectedIndex {
                    DetailView(selectedIndex: theIndex)
                } else {
                    DetailView(selectedIndex: 0)
                }
            }
    }
}
于 2022-02-03T20:54:46.980 回答