SwiftUI mysterious behavior

Hello dear developers! Recently, I stumbled upon some really strange behavior of SwiftUI and I’m very curious why it works this way

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

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

But what really drive me crazy is that if we change a little bit code to this:

I just added another @State property 'number' and use it as the Button's title. In this scenario it works 😃 and Text in the sheet view appearing

struct ContentView: View {
    @State private var title: String?
    @State private var number = 0
    @State private var isSheetPresented = false
    
    var body: some View {
        Button("\(number)") {
            title = "Sheet title"
            number += 0
            isSheetPresented = true
        }
        .sheet(isPresented: $isSheetPresented, content: {
            if let title {
                Text(title)
            } else {
                EmptyView()
            }
        })
    }
}

Is this somehow related to what happens under the hood like View Tree and Render Tree (Attribute Graph)?

Maybe because ContentView’s body doesn't capture title it cannot be stored in the Render Tree so it always would have the initial value of nil?

if there are any well-informed folks here, please help me figure out this mystery, I’d appreciate it!!!

p.s. Don’t get me wrong. Im not interested in 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

I tested your 2 codes on Xcode 16.4 and Xcode 26.2.

Same result for the first.

With the second, different from yours: I still get emptyView.

SwiftUI mysterious behavior
 
 
Q