Consider this SwiftUI view code snippet. What will be printed to the console when the button is tapped once?
import SwiftUI struct ContentView: View { @State private var count = 0 var body: some View { Button("Tap me") { count += 1 print("Count is now \(count)") } } }
Remember @State stores a value that updates when changed.
When the button is tapped, the count increments from 0 to 1, so the print shows "Count is now 1".
Given this Swift class, what will be printed when model.name = "Alice" is executed?
import Foundation import Combine class UserModel: ObservableObject { @Published var name: String = "" } let model = UserModel() let cancellable = model.$name.sink { newName in print("Name changed to: \(newName)") } model.name = "Alice"
@Published triggers updates to subscribers when the property changes.
Assigning "Alice" to name triggers the sink closure, printing the new value.
Look at this code. The view does not update when model.name changes. What is the cause?
import SwiftUI class UserModel: ObservableObject { @Published var name = "" } struct ContentView: View { @ObservedObject var model = UserModel() var body: some View { Text(model.name) } } let model = UserModel() model.name = "Bob"
SwiftUI views must observe ObservableObject with @ObservedObject to update.
Without @ObservedObject, the view does not watch for changes and won't update.
Choose the correct syntax to declare a @State property named isOn initialized to false.
@State properties are usually private vars.
Option A uses correct syntax: @State private var isOn = false
You want a SwiftUI view to update when a shared model's property changes. The model uses @Published. Which approach correctly connects the model to the view's @State?
Think about which property wrapper watches ObservableObject changes.
@ObservedObject watches the model's @Published properties and updates the view. @State is for local state, not shared models.