# Session 226 - Data Flow Through SwiftUI ###### tags: `WWDC-2019` `SwiftUI` https://developer.apple.com/wwdc19/226 - Tools for data flow (正式名稱叫 Property Wrapper) - Property - @Environment - @Binding - @State - BindableObject / @ObjectBinding - Data access as a Dependency - 配合 `Combine.framework` - 想像成 RAC + Redux --- - @State - Each `@State` is a single source of truth - Read and write **with ownership** - Views are a function of state, not of a sequence of events - **Be Careful** - Limit use if possible - Use derived `Binding` or value - Prefer `BindableObject` for presistence - Example: Button highlighting - Most of the time: Good for prototyping, not for practice - @Binding - Read and write **without ownership** - Derivable from `@State` / `@ObjectBinding` / `@Binding` - 用 `$` prefix 存取 data source - First class reference to data - Great for reusability - BindableObject Protocol - External data - Reference type - Great for the model you already have - 透過 `Combine` 送出變化 - @ObjectBinding - 接受符合 `BindableObject` protocol 的 `class` object - `BindableObject` 送出 `didChange()` 時就會收到變化 - @EnvironmentObject - 用在 subview 需要根據 superview 的 model 而變化 - Data applicable to an entire hierarchy - Convenience for indirection - Accent color, right-to-left, and more - 一種 `整個 view 的全域變數` 的概念 - model`.environmentObject()` --- @State 跟 BindableObject 的差異 | @State | BindableObject | | ----------------- | ----------------- | | View-local | External | | Value type | Reference type | | Framework managed | Developer managed |