Weird @Binding behavior, doesn't update the value until I set it into different one

So I have this simple test code to test how I can communicate between two views using @Binding. It's supposed to be simple in which there's a list of buttons that when it's pressed it'll open a simple view showing which value they pick.

   struct SimpleButtonView: View {
    @Binding var bindingValueBool:Bool
    @Binding var bindingValueInt:Int
    var myNumber:Int
    
    var body: some View {
        Button(action: {
            //Change the values
            bindingValueBool = true
            bindingValueInt = myNumber
        }, label: {
          Text("Press me \(myNumber)")
        })
    }
    
}

struct TestView: View {
    @State var bindingValueBool: Bool = false
    @State var bindingValueInt: Int = 0
    
    var body: some View {
        ForEach(1...10, id: \.self){
            SimpleButtonView(bindingValueBool: $bindingValueBool, bindingValueInt: $bindingValueInt, myNumber: $0)
        }.sheet(isPresented: $bindingValueBool, content: {
            
            //This should show the number selected?
            //How come it's sometimes correct sometimes shows default value 0 as if the bindingValueInt hasn't got the updated value yet
            Text("This is the selected number \(bindingValueInt)")
        })
    }
}

Pretty straightfoward right? I thought I did it according to what I understood about properties modifier and swiftui, but the result is weird. It seems the bindingValueInt doesn't updated properly ?

I need to click two different buttons to make sure it works, as if the first click on the button and the first update to those binding properties doesn't get propagated to the main view?

Which is weird because the bindingValueBool is always changed as it never fails to show the new sheet? It's just the other binding property that somehow stays to its default until I click "a different" button?

Can someone help me to understand this? Thanks

Accepted Answer

I remember seeing this somewhere before. The issue is that the contents of the sheet are initially created with the initial value (0) before the sheet is first shown. Subsequent sheet presentations then use the new changed value.

The solution to this is to capture the current variable's value as the sheet is about to be shown. Here is how you would do that:

.sheet(isPresented: $bindingValueBool, content: { [bindingValueInt] in
    // use the captured value which will be correct
    Text("This is the selected number \(bindingValueInt)")
}

Thanks, this does solve the issue but I'm not curious what does this line mean, especially the subscript part ?

content: { [bindingValueInt] in

because I know content is ()->Void that doesn't except any parameter

Weird @Binding behavior, doesn't update the value until I set it into different one
 
 
Q