Bird
0
0

Given the code below, what will be printed when model.count = 5 is executed?

medium📝 Predict Output Q13 of 15
iOS Swift - State Management in SwiftUI
Given the code below, what will be printed when model.count = 5 is executed?
class Model: ObservableObject {
  @Published var count: Int = 0
}

let model = Model()
model.$count.sink { print("Count changed to \($0)") }
ACount changed to 5
BCount changed to 0
CNo output
DCompile error
Step-by-Step Solution
Solution:
  1. Step 1: Understand @Published publisher

    @Published creates a publisher accessible via $property, here $count, which emits new values on change.
  2. Step 2: Analyze sink subscription and assignment

    The sink closure prints the new value when count changes. Setting model.count = 5 triggers the print with 5.
  3. Final Answer:

    Count changed to 5 -> Option A
  4. Quick Check:

    @Published publishes new values = Count changed to 5 [OK]
Quick Trick: Remember: $property publishes changes, sink prints new value [OK]
Common Mistakes:
  • Expecting output before assignment
  • Confusing $count with count
  • Thinking no output without explicit call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes