0
0
iOS Swiftmobile~3 mins

Why @Published properties in iOS Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple tag can make your app update itself like magic!

The Scenario

Imagine you are building an app where you want the screen to update automatically whenever some data changes, like a user's score or a list of messages.

Without any special tools, you have to write extra code to watch for changes and then update the screen manually every time something changes.

The Problem

This manual way is slow and tricky. You might forget to update the screen in some places, causing the app to show old or wrong information.

It's like trying to keep a group chat updated by texting each friend separately instead of using a group chat app.

The Solution

@Published properties in Swift make this easy. When you mark a variable with @Published, Swift automatically watches it for changes.

Whenever the value changes, the app updates the screen or any part that depends on that data without extra code.

Before vs After
Before
var score = 0
func updateScore(newScore: Int) {
  score = newScore
  updateScreen() // must call manually
}
After
@Published var score = 0
// UI updates automatically when score changes
What It Enables

This lets you build apps that react instantly and correctly to data changes, making your app feel smooth and smart.

Real Life Example

Think of a fitness app that shows your step count live. With @Published, the step count on screen updates automatically as you walk, without you needing to refresh anything.

Key Takeaways

@Published properties automatically notify the app when data changes.

This removes the need to write manual update code, reducing errors.

It helps create responsive and user-friendly apps easily.