Swift-UI unpredictable behavior

Why in this case when we tap the button and sheet comes in we go to the branch else even though we set title before isSheetPresented but it still somehow nil

Does it somehow related to under the hood stuff like View Tree and Render Tree?

and because CounterView’s body don’t capture title it cannot be stored in the Render Tree so it always would have the initial value of nil

If there are some well informed guys out here please help me figure this mystery out, I’d appreciate it!!!

struct ContentView: View {
    @State private var title: String?
    @State private var isSheetPresented: Bool = false

    var body: some View {
        Button("Hello, world!") {
            title = "Sheet title"
            isSheetPresented = true
        }
        .sheet(isPresented: $isSheetPresented, content: {

            if let title {
                Text(title)
            } else {
                EmptyView()
            }
        })
    }
}


Hello, @vanjo

This is a SwiftUI question, but these forums are dedicated to the Swift language itself. There is a place for this kind of questions: Apple Developer Forums.

I am not a SwiftUI expert, but you can achieve the desired result by slightly tweaking your code.

struct ContentView: View {
    @State private var isSheetPresented: Bool = false

    var body: some View {
        Button("Hello, world!") {
            isSheetPresented = true
        }
        .sheet (isPresented: $isSheetPresented, content: {
            if let title = sheetTitle {
                Text(title)
            } else {
                Text("Sheet title not set")
            }
        })
    }
    
    var sheetTitle: String? {
        return "Sheet title"
    }
}

But there are a lot of guys who post their troubles with SwiftUI over here

Don’t get me wrong. Im not interested how to make it work. I’m interested in why this doesn’t work and what really happens under the hood that led to this result