0
0
iOS Swiftmobile~5 mins

@Published properties in iOS Swift

Choose your learning style9 modes available
Introduction

@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.

When you want the user interface to change as soon as data changes.
When you have a value that many parts of your app need to watch and react to.
When you want to keep your code simple and avoid manual updates.
When building apps with SwiftUI that need to show live data updates.
Syntax
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.

Examples
This example creates a counter that updates any view watching count when it changes.
iOS Swift
class Counter: ObservableObject {
  @Published var count: Int = 0
}
Multiple @Published properties can be used in one class to track different pieces of data.
iOS Swift
class UserSettings: ObservableObject {
  @Published var username: String = "Guest"
  @Published var isLoggedIn: Bool = false
}
Even if the initial value is empty, views will update when the property changes later.
iOS Swift
class EmptyModel: ObservableObject {
  @Published var text: String = ""
}
Sample App

This app shows a number that increases every second after you press the button. The @Published property secondsElapsed updates the text automatically.

iOS Swift
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()
    }
  }
}
OutputSuccess
Important Notes

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.

Summary

@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.