Fix the leak model for a polling view model

Review the AI's codeEasy10 minApple style

Your task

An AI assistant wrote a SwiftUI view model that polls a feed with a repeating Timer, and the timer's closure captures self strongly. The run loop keeps the timer, the timer keeps its closure, and the closure keeps the view model, so every visit to the screen leaks one. Your team models the two possible fixes to see what survives a run of navigations.

An assistant wrote simulate_view_model_leak(lifecycle_events, weak_capture, invalidate_on_disappear), the model. It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • lifecycle_events: the navigation log, in order. appear opens the screen, which creates a new view model and a new repeating timer. disappear closes the most recently opened screen that is still open.
  • weak_capture: the timer's closure captures self weakly, with [weak self].
  • invalidate_on_disappear: closing a screen calls invalidate() on its timer.
  • Return a list of two numbers: the view models still alive, then the timers still scheduled.

Rules the tests check:

  • Ignore any other event, and ignore disappear when no screen is open.
  • When a screen closes and invalidate_on_disappear is true, its timer stops and its view model is freed.
  • When a screen closes, invalidate_on_disappear is false and weak_capture is true, its view model is freed, but its timer stays scheduled and keeps firing.
  • When a screen closes and both are false, nothing is freed.
  • Nothing else frees a view model or stops a timer.

Examples

simulate_view_model_leak(lifecycle_events: list[str], weak_capture: bool, invalidate_on_disappear: bool) -> list[int]
Example 1
Inputsimulate_view_model_leak(["appear", "disappear", "appear", "disappear", "appear", "disappear"], False, False)
Output[3, 3]
Example 2
Inputsimulate_view_model_leak(["appear", "disappear", "appear", "disappear", "appear", "disappear"], False, True)
Output[0, 0]