0
0
Swiftprogramming~15 mins

Built-in property wrappers (@State, @Published) in Swift - Deep Dive

Choose your learning style9 modes available
Overview - Built-in property wrappers (@State, @Published)
What is it?
Built-in property wrappers in Swift, like @State and @Published, are special tools that help manage data that can change over time. They automatically keep track of changes and update the user interface or other parts of your app when the data changes. This makes it easier to write apps that respond smoothly to user actions or data updates without extra code. They are commonly used in SwiftUI and Combine frameworks.
Why it matters
Without property wrappers like @State and @Published, developers would have to manually track changes and update the UI or other parts of the app, which is error-prone and tedious. These wrappers simplify reactive programming, making apps more responsive and reducing bugs. They help keep code clean and focused on what the app should do, not how to keep everything in sync.
Where it fits
Before learning property wrappers, you should understand basic Swift variables and how SwiftUI or Combine frameworks work. After mastering these wrappers, you can explore custom property wrappers, advanced state management, and reactive programming patterns in Swift.
Mental Model
Core Idea
Property wrappers like @State and @Published automatically watch a variable for changes and notify the system to update dependent parts, like the UI, without manual intervention.
Think of it like...
It's like having a smart assistant who watches your important notes and immediately tells everyone who needs to know whenever you change something, so no one is left out of date.
┌───────────────┐       change       ┌───────────────┐
│  @State var   │ ───────────────▶ │ UI updates     │
│  or @Published│                   │ or subscribers │
└───────────────┘                   └───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Swift Variables
🤔
Concept: Learn what variables are and how they store data in Swift.
In Swift, a variable is a named container that holds a value which can change over time. For example, var count = 0 means count holds the number 0, and you can change it later by assigning a new number.
Result
You can store and change data using variables in Swift.
Knowing how variables work is essential because property wrappers build on this basic idea by adding automatic change tracking.
2
FoundationIntroduction to Property Wrappers
🤔
Concept: Property wrappers add extra behavior to variables automatically.
A property wrapper is a special Swift feature that wraps around a variable to add functionality. For example, @State wraps a variable to make it reactive in SwiftUI. You write @State var name = "" and Swift handles updates for you.
Result
Variables can now have extra powers like automatic updates.
Understanding that property wrappers are a layer around variables helps you see how they add features without changing how you use variables.
3
IntermediateHow @State Works in SwiftUI
🤔Before reading on: do you think @State variables are shared across views or unique to each view instance? Commit to your answer.
Concept: @State stores data that belongs to a single SwiftUI view and triggers UI updates when changed.
When you declare @State var count = 0 inside a SwiftUI view, SwiftUI keeps track of this data separately for each view instance. When count changes, SwiftUI automatically redraws the parts of the UI that depend on it.
Result
UI updates automatically when @State variables change, keeping the interface in sync with data.
Knowing @State is local to a view explains why it’s perfect for simple, view-specific data that changes over time.
4
IntermediateHow @Published Works with ObservableObject
🤔Before reading on: do you think @Published works alone or needs a special class to notify changes? Commit to your answer.
Concept: @Published marks properties inside ObservableObject classes to notify subscribers when data changes.
You create a class conforming to ObservableObject and mark variables with @Published. When these variables change, any SwiftUI view or Combine subscriber watching the object gets notified and updates accordingly.
Result
Changes in @Published properties propagate to all subscribers, enabling reactive data flow.
Understanding that @Published works with ObservableObject shows how to manage shared data across multiple views or components.
5
IntermediateDifference Between @State and @Published
🤔Before reading on: do you think @State and @Published serve the same purpose or different roles? Commit to your answer.
Concept: @State is for local view state, while @Published is for shared, observable data in classes.
@State keeps data inside a single view and triggers UI updates there. @Published is used inside ObservableObject classes to broadcast changes to many listeners, often across multiple views.
Result
You can choose the right wrapper depending on whether data is local or shared.
Knowing the roles helps avoid bugs like trying to share @State data or misusing @Published for local state.
6
AdvancedMemory and Lifecycle of @State Variables
🤔Before reading on: do you think @State variables live as long as the app or only as long as the view? Commit to your answer.
Concept: @State variables are stored outside the view struct and tied to the view’s lifecycle.
SwiftUI stores @State data separately from the view struct because views are recreated often. The system keeps @State alive as long as the view is in the UI hierarchy, preserving data across redraws.
Result
@State variables maintain their values even when views refresh, ensuring consistent UI behavior.
Understanding this prevents confusion about why @State values don’t reset on every UI update.
7
ExpertHow @Published Sends Change Notifications
🤔Before reading on: do you think @Published uses manual calls or automatic mechanisms to notify changes? Commit to your answer.
Concept: @Published uses Combine’s Publisher protocol to automatically emit change events when the property changes.
Behind the scenes, @Published creates a publisher that emits a signal every time the property’s value changes. Subscribers listen to this publisher and react accordingly, enabling reactive programming.
Result
Data changes flow automatically through Combine pipelines without manual notification code.
Knowing this reveals how Swift’s reactive system is built on Combine’s powerful publisher-subscriber model.
Under the Hood
@State stores its wrapped value in a special storage managed by SwiftUI, separate from the view struct, to survive view reloads. When the value changes, SwiftUI marks the view as needing refresh. @Published wraps a property with a Combine publisher that emits events on value changes, notifying all subscribers automatically.
Why designed this way?
SwiftUI’s design treats views as lightweight, transient structs rebuilt often for performance and simplicity. To keep state persistent, @State stores data externally. Combine’s reactive model inspired @Published to provide automatic, declarative change notifications, avoiding manual observer code.
┌───────────────┐       change       ┌───────────────┐
│  @State var   │ ───────────────▶ │ SwiftUI marks  │
│  (external    │                   │ view for redraw│
│  storage)     │                   └───────────────┘
└───────────────┘

┌───────────────┐       change       ┌───────────────┐
│ @Published var│ ───────────────▶ │ Combine sends  │
│ (publisher)   │                   │ event to subs │
└───────────────┘                   └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does @State share data between different views automatically? Commit to yes or no.
Common Belief:@State variables automatically share their data across multiple views.
Tap to reveal reality
Reality:@State variables are local to the view instance and do not share data between views.
Why it matters:Assuming @State shares data can lead to bugs where views show inconsistent or outdated information.
Quick: Can @Published be used outside ObservableObject classes? Commit to yes or no.
Common Belief:@Published works on any variable in any class or struct.
Tap to reveal reality
Reality:@Published only works inside classes conforming to ObservableObject.
Why it matters:Using @Published outside ObservableObject causes compiler errors and breaks reactive updates.
Quick: Does changing an @Published property always update the UI immediately? Commit to yes or no.
Common Belief:Changing an @Published property instantly updates the UI without delay.
Tap to reveal reality
Reality:UI updates happen asynchronously after the change notification, not instantly.
Why it matters:Expecting immediate UI updates can cause confusion and incorrect assumptions about app behavior.
Quick: Is @State suitable for storing large shared data models? Commit to yes or no.
Common Belief:@State is ideal for storing large, shared data models across the app.
Tap to reveal reality
Reality:@State is designed for small, local state; large shared data should use ObservableObject with @Published.
Why it matters:Misusing @State for large shared data leads to poor performance and complicated code.
Expert Zone
1
Using @State with complex data types requires careful handling to avoid unnecessary view reloads due to value semantics.
2
@Published properties emit change events even if the new value is equal to the old one, which can cause redundant updates unless filtered.
3
Combining @State and @Published in the same view requires understanding their different lifecycles and ownership to avoid bugs.
When NOT to use
@State should not be used for data that needs to be shared across multiple views or persisted beyond the view lifecycle; use ObservableObject with @Published instead. Avoid @Published in structs or non-ObservableObject classes as it won't work properly.
Production Patterns
In real apps, @State is used for simple UI flags like toggles or counters, while @Published inside ObservableObject manages shared data like user settings or network responses. Developers often combine these with Combine operators for advanced reactive flows.
Connections
Observer Pattern
Built-in property wrappers implement the observer pattern automatically.
Understanding property wrappers as automatic observers clarifies how data changes trigger updates without manual listener code.
Reactive Programming
Property wrappers like @Published are foundational to reactive programming in Swift.
Knowing how @Published connects to Combine’s reactive streams helps grasp the flow of data and events in modern Swift apps.
Event-driven Systems (Computer Science)
Property wrappers enable event-driven updates similar to event listeners in broader computing.
Seeing property wrappers as event emitters links SwiftUI’s reactive model to general event-driven programming concepts.
Common Pitfalls
#1Trying to share @State data between views directly.
Wrong approach:struct ContentView: View { @State var count = 0 var body: some View { VStack { Text("Count: \(count)") ChildView(count: $count) } } } struct ChildView: View { @State var count: Int var body: some View { Button("Increment") { count += 1 } } }
Correct approach:struct ContentView: View { @State var count = 0 var body: some View { VStack { Text("Count: \(count)") ChildView(count: $count) } } } struct ChildView: View { @Binding var count: Int var body: some View { Button("Increment") { count += 1 } } }
Root cause:Misunderstanding that @State is local and must be passed as a binding to share mutable state.
#2Using @Published in a struct or non-ObservableObject class.
Wrong approach:struct DataModel { @Published var value = 0 }
Correct approach:class DataModel: ObservableObject { @Published var value = 0 }
Root cause:Not knowing @Published requires ObservableObject conformance to work properly.
#3Expecting immediate UI update after changing @Published property.
Wrong approach:viewModel.value = 10 print("UI updated") // assumes UI updated immediately
Correct approach:viewModel.value = 10 // UI updates asynchronously after this line
Root cause:Assuming synchronous UI updates without understanding Combine’s asynchronous event delivery.
Key Takeaways
@State and @Published are Swift’s built-in tools to automatically track and react to data changes.
@State is for local view state, while @Published works with ObservableObject for shared data.
These wrappers simplify keeping UI and data in sync without manual update code.
Understanding their lifecycles and roles prevents common bugs and improves app design.
They are foundational to reactive programming in Swift and connect to broader observer and event-driven patterns.