@Published properties help your app update the screen automatically when data changes. This means you don't have to write extra code to refresh the view.
@Published properties in iOS Swift
class MyModel: ObservableObject { @Published var myValue: String = "" }
The class must conform to ObservableObject to use @Published.
Properties marked with @Published automatically notify views when they change.
count when it changes.class Counter: ObservableObject { @Published var count: Int = 0 }
@Published properties can be used in one class to track different pieces of data.class UserSettings: ObservableObject { @Published var username: String = "Guest" @Published var isLoggedIn: Bool = false }
class EmptyModel: ObservableObject { @Published var text: String = "" }
This app shows a number that increases every second after you press the button. The @Published property secondsElapsed updates the text automatically.
import SwiftUI class TimerModel: ObservableObject { @Published var secondsElapsed: Int = 0 func startTimer() { Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in self?.secondsElapsed += 1 } } } struct ContentView: View { @StateObject private var timerModel = TimerModel() var body: some View { VStack { Text("Seconds: \(timerModel.secondsElapsed)") .font(.largeTitle) .padding() Button("Start Timer") { timerModel.startTimer() } .padding() } } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
Time complexity: Updating a @Published property is very fast, just a simple value change.
Space complexity: Minimal extra memory is used for the publisher behind the scenes.
Common mistake: Forgetting to mark the class as ObservableObject or forgetting to use @StateObject or @ObservedObject in the view to watch the changes.
Use @Published when you want automatic UI updates. Use manual updates only if you need more control.
@Published makes properties send updates automatically.
Use it inside classes that conform to ObservableObject.
It helps keep your UI in sync with your data easily.