why is @state being reset after alert dismissal

Viewed 158

complete SwiftUI beginner here. I'm looking at this example and I'm trying to understand the lifecycle of @state variables.

showingAlert is initialized as false and is set to true when the button is tapped. the part that I have trouble wrapping my head around is why does it reset back to false when the alert is dismissed? I do not set that to false anywhere.

I expected it to remain true

@State private var showingAlert = false

var body: some View {
   Button(action: { self.showingAlert = true }
   ) { 
     Text("Show Alert")
   }
   .alert(isPresented: $showingAlert) {
     Alert(title: Text("Important message"))
   }
}
1 Answers

Because, by definition, if the alert is dismissed, the alert is no longer presented. $showingAlert is a binding — it moves data in both directions. Its value is always correlated to whether the alert is being presented; that's what it means to be a binding.

Related