Can Apple's SwiftUI @State and @Binding example do anything?

Am referring Apple's @State documentation: https://developer.apple.com/documentation/swiftui/state

How does an outside class or struct observe a change in @State within a SwiftUI View?

For example, using Apple's Button example in the link above, how would a change in @State isPlaying actually do something like start or stop a media player? Do I attach a callback, use a KVO, or use a special observer?

Replies

You use State to represent some state of your view. You always declare State as private, because it isn't meant to be visible above the view in which you declare it. You can pass it down the hierarchy to subviews as a parameter so they can read it, or as a Binding so they can read or modify it. So it's good for managing aspects of your view that are completely local, and great for prototyping while you design your view and figure out what exactly needs to be modeled.

If you also need the information outside your view hierarchy, you'll want to store that in a model of some kind, and provide it to both your views and whatever other logic needs it. For example, you can instantiate your model as a StateObject in your app, and pass that around to whatever logic needs it, either as an environment object, or through input parameters.

So, the Apple button example for @State has no real utility as a button.

To be honest, I find a View's ability to interleave (procedural) state with (declarative) layout and gestures to be rather complex.

Currently, am using a MVVM pattern; a combination of Model, ViewModel (or Vm), and View. The Vm is passed as an @ObservedObject and receives the View's .onAppear and .onChange messages. This eliminates the View's need for @State, @Binding, and @StateObject. So, the Vm focuses on the state machine, while the View focuses on layout and dispatching gestures.

A Vm class can also persist and synchronize across devices, such as iWatch-iPhone-iPad-AppleTv-SharePlay, etc. But, maybe there is a better way of accomplishing the same goals with a self modifying struct. I dunno; still trying to wrap my head around the best approach.

Thanks.