SwiftUI state not updated as non-binding parameter ?

Temas RE
2 min readFeb 19, 2023

In SwiftUI, a state is a value type that allows a view to store and update its own data. A state property is declared using the @State property wrapper, which creates a binding between the view and the value stored in the state property. When the value of the state property changes, SwiftUI automatically updates the view to reflect the new value.

When you pass a state property as a non-binding parameter to a child view, the child view receives a copy of the state property’s value, not the binding itself. This means that changes to the value of the state property in the child view will not be reflected in the parent view, because the child view is working with a separate copy of the value.

To allow a child view to update a parent view’s state property, you need to pass the state property as a binding parameter. This creates a binding between the parent and child views, allowing the child view to modify the parent view’s state property directly.

Here’s an example to illustrate the difference between a non-binding parameter and a binding parameter:

swiftCopy code
struct ParentView: View {
@State private var count = 0

var body: some View {
ChildView(count: count) // non-binding parameter
// ChildView(count: $count) // binding parameter
}
}
struct ChildView: View {
var count: Int // non-binding parameter
// @Binding var count: Int // binding parameter

var body: some View {
Button("Increment Count") {
count += 1 // Does not update parent view's state when count is a non-binding parameter
// self.count += 1 // Updates parent view's state when count is a binding parameter
}
}
}

In the example above, if count is passed as a non-binding parameter to ChildView, changes to count in ChildView will not be reflected in the parent view's state. However, if count is passed as a binding parameter, changes to count in ChildView will update the parent view's state.

--

--