DEV Community

Discussion on: SwiftUI @State and @Binding

Collapse
 
thetealpickle profile image
✨ thetealpickle πŸ“± • Edited

YES!

So with SwiftUI the State and Binding are ways for the views to have access to a consistent source of truth. State creates an instance of truth, whereas Binding passes a reference. Binding is useful when you want to pass a select subsection of data that can be mutated by child views. Binding assures the mutated data remains synced with your source of truth (often State, but can also be an EnvironmentObject or @ObservedObject)

ObservableObject (protocol) and @Published are ways to conform your custom classes to the declarative paradigm. The class itself, when conformed to ObservableObject can then be passes in as an EnvironmentObject and shared everywhere. An ObservableObject can also be used with @ObservedObject to invalidate views when there are any changes. Published is used to mark specific class properties which can be mutated by your views. Published properties can be used wherever a State or Binding is asked.

When referring to view invalidation, what are we talking about?
Any changes that would trigger the compiler to generate a new view.
Properties that would change a view's data essentially, invalidates the view.
AND, luckily for us, views are structs so they're cheaper to replace than a class counterpart (by value vs. by reference)

Hope this helped !! 😊