Member-only story

Property Wrappers in SwiftUI

Property Wrapper

When we work with SwiftUI, It's very important to understand the property wrappers because SwiftUI forces you to Bind the data with UI(2-way binding). In this way, we can reduce the amount of boilerplate in our code.

StateObject

The @StateObject property wrapper in SwiftUI is used to create and manage an instance of a class that conforms to ObservableObject. It allows you to create and manage the lifecycle of reference types while ensuring that the view is updated whenever the observed properties of that class change.

Example:

class CounterModel: ObservableObject {
@Published var count = 0 // @Published triggers view updates when 'count' changes
func increment() {
count += 1
}
}

// Use @StateObject in a SwiftUI View
struct CounterView: View {
@StateObject private var counter = CounterModel() // SwiftUI owns and manages this object

var body: some View {
VStack(spacing: 20) {
Text("Count: \(counter.count)") // Updates automatically when 'count' changes
Button(action: {
counter.increment() // Increment count
}) {
Text("Increment")…

--

--

Responses (2)