SwiftUI sheet closure capture list syntax

402 views Asked by At

How would I add capture list to a SwiftUI .sheet(content: ) closure?

I have a sheet in SwiftUI and in the content: closure I check the value of an optional to determine which view to show. The first time it is run the value is alway nil even if I've set it beforehand. I submitted a bug report and Apple says if I reference the variable in the closure's capture list then it will work as expected. I'm new to SwiftUI and haven't been able to figure out the proper syntax for doing so. What is the syntax?

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)
                    }
                }
            }
    }
}
1

There are 1 answers

1
Patrick Wynne On BEST ANSWER

This compiles.

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)
                }
            }
    }
}