Kuba Suder's blog on Mac & iOS development


App ClipsAppKitCloudKitExtensionsFoundationiCloudLocationLoggingMacMapsPerformancePhotosPrivacySafariSwiftSwiftUIUIKitWatchKitWWDC 12WWDC 14WWDC 15WWDC 16WWDC 18WWDC 19WWDC 20WWDC 21

View as index

Data Flow Through SwiftUI

Categories: SwiftUI, WWDC 19 0 comments Watch the video

(*) marks APIs that were changed since the video was published

Every source of truth in the UI (= piece of information on which the UI depends) should only be defined in one place and used from there, not in many places which have to be kept in sync

A @State is a (private) source of truth handled and used by this specific view

→ it’s good to mark it as private

View is a function of state, not a result of a sequence of add/modify/delete events like in UIKit

Traditionally, you would modify views over the life of the app; in SwiftUI, you modify the state and data on which the UI depends

User interacts with UI  ⭢  action is performed  ⭢  action mutates some state  ⭢  system detects that the view needs to be re-rendered and updates it

The framework allows you (and encourages you!) to build small views that represent a single piece of data, that can be composed together

When an external event happens that needs to update the view, the change is funneled through the same chain as user actions

External events use an abstraction from Combine called Publisher

(they need to be received on the main thread!)

Read-only data (plain Swift properties, environment) is preferred when data does not need to be mutated.

Most of the time your data lives outside of the UI, so State normally has limited use.

If you find yourself adding @State, take a step back and think if this data really needs to be owned by this view. Perhaps it should instead be moved to a parent, or maybe it should be represented by an external source added as an ObservableObject (*)