Complete the code to declare an observable object using @StateObject in a SwiftUI view.
struct ContentView: View {
@StateObject var viewModel = [1]()
var body: some View {
Text(viewModel.title)
}
}You use your custom class name that conforms to ObservableObject with @StateObject to create and own it in the view.
Complete the code to update the view when the observable object changes.
class MyViewModel: ObservableObject { @Published var count = 0 } struct ContentView: View { @StateObject var viewModel = MyViewModel() var body: some View { Button(action: { viewModel.[1] += 1 }) { Text("Count: \(viewModel.count)") } } }
The @Published property 'count' is updated to trigger the view refresh.
Fix the error in the code by completing the declaration of the observable object in the view.
struct ContentView: View {
[1] var viewModel = MyViewModel()
var body: some View {
Text("Count: \(viewModel.count)")
}
}@StateObject is used to create and own the observable object in the view lifecycle.
Fill both blanks to declare an observable object class and use it with @StateObject in a SwiftUI view.
class [1]: ObservableObject { @Published var message = "Hello" } struct ContentView: View { @StateObject var viewModel = [2]() var body: some View { Text(viewModel.message) } }
The class name and the instance type must match exactly for the code to compile and work.
Fill all three blanks to create an observable object with a published property and use it in a SwiftUI view with @StateObject.
class [1]: ObservableObject { @Published var [2] = 0 } struct ContentView: View { @StateObject var viewModel = [3]() var body: some View { Text("Value: \(viewModel.value)") } }
The class name and instance must match, and the published property name must be consistent with the usage in the view.