DevPrep

All topics › SwiftUI

How do state management and single source of truth work?

Middle PRO

The principle

Every fact in the app must have one place where it is stored, and everything else is derived from it. The UI in SwiftUI is a pure function of state: view = f(state). Data flows one way: state → body → screen; user actions mutate the state, and the framework re-evaluates the dependent views itself. Duplicated state (a copy of an array in a child view, a flag "cached" in two places) leads to desync and bugs that show up only under a specific sequence of actions.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store