use @published in swift

In Swift, @Published is a property wrapper that allows us to declare a property in a class or struct as an observable property. Whenever a value of a property annotated with @Published changes, any subscribed views will be notified of the change and get updated.

Here is an example of how to use @Published property wrapper:

main.swift
import SwiftUI
import Combine

class ViewModel: ObservableObject {
    @Published var value: String = "Initial value"
}

struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        VStack {
            Text(viewModel.value)
            Button("Update Value") {
                viewModel.value = "New value" // this will trigger the value change notification
            }
        }
    }
}
440 chars
20 lines

In the above example, we have declared a ViewModel class with a single property value marked with @Published. Then we have created a view called ContentView and instantiated ViewModel as an @ObservedObject. Finally, we have provided a button to the view that changes the value of the viewModel.value property, which will trigger the notification and update the view.

gistlibby LogSnag