Bird
0
0

Consider the following SwiftUI code:

medium📝 Predict Output Q4 of 15
iOS Swift - State Management in SwiftUI
Consider the following SwiftUI code:
class ScoreTracker: ObservableObject {
  @Published var score = 0
  func increment() {
    score += 1
  }
}

struct ScoreView: View {
  @ObservedObject var tracker: ScoreTracker
  var body: some View {
    VStack {
      Text("Score: \(tracker.score)")
      Button("Add Point") {
        tracker.increment()
      }
    }
  }
}

What will be displayed after the "Add Point" button is tapped twice?
AThe app will crash due to missing @StateObject
BScore: 0
CScore: 1
DScore: 2
Step-by-Step Solution
Solution:
  1. Step 1: Understand @ObservedObject behavior

    The @ObservedObject property wrapper listens for changes in the ObservableObject and updates the view when a @Published property changes.
  2. Step 2: Analyze the increment function

    Each tap on the button calls increment(), which increases score by 1 and triggers a view update.
  3. Step 3: Calculate the final score

    After two taps, score will be 2, so the text will display "Score: 2".
  4. Final Answer:

    Score: 2 -> Option D
  5. Quick Check:

    Button taps increment score correctly [OK]
Quick Trick: Button taps update @Published properties triggering view refresh [OK]
Common Mistakes:
  • Assuming the score resets after each tap
  • Confusing @ObservedObject with @StateObject ownership
  • Believing the view won't update without @StateObject

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes