DevPrep

All topics › SwiftUI

How do you pass data down and events up: let, @Binding, closures, Environment, PreferenceKey?

Middle PRO

The gist

In SwiftUI data flows down the tree and events flow up. Each direction has several tools, and the choice depends on two questions: who owns the data, and how many levels lie between the sender and the receiver.

Down: a let property (read-only), @Binding (read and write someone else's state), Environment (implicitly across many levels). Up: a closure (an event, an intent), the same @Binding (writing a value) and PreferenceKey (values from descendants collected by an ancestor).

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