SwiftUI how to change a value of @published var

Asked on 09/06/2024

1 search

To change the value of a @Published variable in SwiftUI, you typically use a @State or @Binding property to manage the state within your view. SwiftUI automatically updates the UI when the state changes. Here's a brief explanation based on the context from the "SwiftUI essentials" session:

  1. State Management: SwiftUI uses state-driven views, meaning that when your view's state changes, SwiftUI automatically updates the UI. This is achieved using properties like @State and @Binding.

  2. Using @State: You can declare a @State property in your view to manage its internal state. When you modify this state, SwiftUI will re-render the view to reflect the changes. For example, if you have a button that increments a counter, you would use a @State property to store the counter value.

  3. Using @Binding: If you need to pass state between views, you can use @Binding. This creates a two-way connection between a parent view's state and a child view's state, allowing the child view to read and write the parent's state.

Here's a simple example:

struct ContentView: View {
    @State private var counter: Int = 0

    var body: some View {
        VStack {
            Text("Counter: \(counter)")
            Button("Increment") {
                counter += 1
            }
        }
    }
}

In this example, the counter is a @State property. When the button is tapped, the counter is incremented, and SwiftUI automatically updates the Text view to display the new counter value.

For more detailed information, you can refer to the SwiftUI essentials session, which discusses state management and how SwiftUI handles UI updates.