How to choose SwiftUI PropertyWrappers

We have @State, @StateObject, @EnvironmentObject, @ObservedObject, @ObservableObject, @Published. @Binding

First I recommend Checking out Data Essentials in SwiftUI WWDC.

  1. What does this view need to do its job?
  2. How will the view manipulate the data?
  3. Where will the data come from?
  • Note: Pull out related properties into their own struct.

let:

When the view doesn’t change the value nor have power to, then use let alone without property wrappers. The data will come from the superview somewhere higher up the view hierarchy.

@State:

When the view can change the value. When the value isn’t passed in as a reference. Should usually be a struct. Creates a new source of truth, not a shared source of truth.

@Binding:

A binding is a source of truth that is shared accross views. It allows the current view to make changes on its superview. And it allows itself to change the value.

If a binding property is a struct it could clear the values accidentally when the new struct is instantiated, by creating an empty new instance when the super views are refreshed and not a copy of a reference to the object. If this happens, then you may be able to convert your binding to a state.

10:37 minutes in.

@StateObject:

@EnvironmentObject:

@ObservedObject:

@ObservableObject:

@Published:

@Binding: