What if your app could update itself instantly without you writing extra code to watch for changes?
Why Built-in property wrappers (@State, @Published) in Swift? - Purpose & Use Cases
Imagine you are building an app where you want to update the screen whenever a user changes a value, like typing in a text box or toggling a switch. Without special tools, you would have to write extra code to watch for changes and then update the screen manually.
This manual way is slow and tricky. You might forget to update the screen, causing the app to show old information. It's easy to make mistakes, and the code becomes messy and hard to fix.
Built-in property wrappers like @State and @Published automatically watch for changes in your data. When the data changes, they tell the app to update the screen right away. This makes your code cleaner, simpler, and less error-prone.
var name: String = "" // manually update UI when changed@State var name: String = "" // UI updates automaticallyThey let your app react instantly to data changes, creating smooth and dynamic user experiences without extra effort.
When a user types in a search box, @State updates the search text, and the app immediately shows matching results without you writing extra update code.
@State and @Published automatically track changes in data.
They reduce manual update code and bugs.
They help build interactive, responsive apps easily.
Practice
@State property wrapper in SwiftUI?Solution
Step 1: Understand what
@Statedoes@Stateis used to keep simple, local data inside a SwiftUI view.Step 2: Recognize its effect on UI
When the@Statedata changes, SwiftUI automatically updates the view to reflect the new data.Final Answer:
To store local, simple data inside a view and update the UI when it changes -> Option CQuick Check:
@Statemanages local view data = B [OK]
- Confusing @State with @Published
- Thinking @State is for class properties
- Assuming @State handles network or async tasks
@Published property inside a Swift class?Solution
Step 1: Identify where
@Publishedcan be used@Publishedis used inside classes that conform toObservableObject, not structs.Step 2: Check syntax correctness
class MyClass { @Published var count: Int = 0 } correctly declares a class with a@Publishedproperty and initializes it.Final Answer:
class MyClass { @Published var count: Int = 0 } -> Option DQuick Check:
@Publishedused in classes = A [OK]
- Using @Published in structs
- Confusing @State with @Published
- Missing var keyword or initialization
class Counter: ObservableObject {
@Published var value = 0
}
struct ContentView: View {
@StateObject var counter = Counter()
var body: some View {
VStack {
Text("Count: \(counter.value)")
Button("Increment") {
counter.value += 1
}
}
}
}
What will be displayed after tapping the "Increment" button twice?Solution
Step 1: Understand the initial state
TheCounterclass starts withvalue = 0. The view shows "Count: 0" initially.Step 2: Analyze button action and updates
Each tap on "Increment" increasescounter.valueby 1. After two taps, value becomes 2, and the UI updates automatically.Final Answer:
Count: 2 -> Option BQuick Check:
2 increments update value to 2 [OK]
- Forgetting @Published triggers UI update
- Assuming @StateObject resets value
- Counting taps incorrectly
class Model: ObservableObject {
@Published var text: String
init() {}
}
struct ViewContent: View {
@StateObject var model = Model()
var body: some View {
Text(model.text)
}
}Solution
Step 1: Check property initialization
The@Publishedpropertytextis declared but not initialized, and the init() is empty.Step 2: Understand Swift requirement for properties
All non-optional properties must have an initial value or be initialized in the constructor. Here,textlacks both.Final Answer:
Missing initial value for @Published property 'text' in Model -> Option AQuick Check:
Uninitialized property causes error = A [OK]
- Assuming @StateObject can't be used with ObservableObject
- Thinking Text can't display String
- Believing Model must be a struct
Solution
Step 1: Understand data sharing between views
When multiple views need to share and update data, use an ObservableObject class with@Publishedproperties.Step 2: Use
The main view can use@Statefor local view data and@Publishedfor shared data@Statefor local state, but the shared user name should be in a class marked with@Publishedto notify changes.Final Answer:
Use@Statein the main view and@Publishedin a shared ObservableObject class -> Option AQuick Check:
Shared data uses @Published; local uses @State [OK]
- Using @State only for shared data
- Using @Published in structs or views directly
- Not using ObservableObject for shared data
Ready to prove it?
Pass the test and this pattern moves unknown
