Passing data between view controllers

UIKit Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A detail screen edits an item, and the list must update when it saves. Best approach?

Options
Hint 1 of 1

How does the child talk back without knowing the parent?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A The list creates the detail with onSave: (Item) -> Void (or sets a weak delegate) and updates itself in the callback

Correct. The dependency is explicit and decoupled.

Why not the others?
  • B Post a global Notification from the detail. It is untyped and global, so any object can react and flows are hard to trace.
  • C (presentingViewController as! ListViewController).update(item). It couples the screens and crashes if the hierarchy changes.
  • D Mutate a singleton and hope the list refreshes. Nothing tells the list to update.

30-second answer

Forward: inject data through the initializer or properties before presenting. Backward: give the child a closure (onSave) or a weak delegate that the parent sets. For data many screens share, use a shared model object that both observe. Avoid reaching into other controllers or broadcasting with NotificationCenter for screen-to-screen data.

Practise saying it · 30 s. No recording, just a timer

Explain how you pass data between screens.

Say your answer out loud, then check which of these points you covered:

  • Forward via init
  • Backward via closure or delegate
  • Shared model for shared state

Deep dive

Initializer injection makes dependencies explicit and testable.

Closures are lighter than delegate protocols for one callback.

Coordinators own the flow so view controllers don't know about each other.

With storyboards, prefer instantiateViewController(identifier:creator:) for injection.

Common mistakes

  • Casting presentingViewController to a concrete type.
  • Global singletons for screen state.

Senior take & follow-ups

Seniors choose by direction and scope, and keep controllers decoupled.

Follow-up questions

Think of your answer first, then open the hint.

  1. Delegate or closure?

    Show hint

    Closure for one or two callbacks, delegate for a rich protocol.

  2. How do you inject into storyboard controllers?

    Show hint

    The creator closure (iOS 13+).

Suggest a fix if something here is wrong or out of date.