SwiftUI – Data for Views

≫ Back to Comics

SwiftUI is Apple’s newish UI framework, where you textually specify interfaces in Swift. One of the challenges of working with SwiftUI is understanding how to get data to a View.

The images below are the core content of the PDF version, which adds a table of contents, three reference pages about environment variables, and a code sample.

Buy the PDF ($5)

Click on a thumbnail below to see the full-sized image.

Value Owned by ViewPeek Into BindingObservable ObjectsViews with Classes
EnvironmentObjectUser DefaultsEnvironment
  1. SwiftUI – Value Owned by View
Value objects are declared with @State at the top view, declared with @Binding in the child views, and passed to the child with $

2. SwiftUI – A Peek Into @Binding

3. SwiftUI – ObservableObject for (some) Model Classes

A model may be complex, built from many objects. Some of those objects let views see their state or trigger behavior. For classes, implement ObservableObject and mark mutable fields with @Published. This helps SwiftUI figure out which views to update.

4. SwiftUI – Views Working with Classes

The model class is an ObservableObject with Published fields. The owning view declares it with @StateObject. Child views declare it with @ObservedObject.

5. SwiftUI – @EnvironmentObject to Share Data Directly

If you create a @StateObject and pass that into .environnmentObject() on the view, descendant views can use @EnvironmentObject to access it directly, rather than passing it through intermediate views.

6. SwiftUI – Views Using User Default Data

You can use @AppStorage to get or set user defaults. It persists between runs of the app.

7. SwiftUI – Views That Read or Change the Environment

Buy the PDF ($5)

Questions or suggestions? Reach out to me at bill@xp123.com.

≫ Back to Comics