The documentation says that Bindable is “a property wrapper type that supports creating bindings to the mutable properties of observable objects” but I tried and this can also be achieved using the good old Binding. Is there any advantage in using Bindable except for not requiring to reference a State using $? Can I use Binding if I prefer it? For me, it gives more clarity at the point of use that the view will binding to a property of that object.
The most performant way I found to do injection of viewModels while keeping the @StateObject performance is to use this specific syntax. Is there a better way of achieving property injection into state objects?
In iOS 16, we could use @StateObject to declare data that a View owns, while @ObservableObject was for data injected into a View that the View didn't own, and it was pretty easy to create bindings to a property on either a @StateObject or an @ObservableObject.
Unlike @Observable
available starting from iOS17, @State
attribute is not new, but it didn’t use to handle reference types before. If I target iOS 16 (or earlier), should I continue using @StateObject
, or should I start using @State
even while using the old ObservableObject
protocol and @Published
properties?
If I accidentally use @State on a class that does not have the Observable macro (ie before iOS 17) is there a warning at compile/runtime?
When you access an @Observable object via the @Environment property wrapper, is it possible to create bindings to its properties? Using @Bindable doesn't work here, right?
We arrived at a policy of never using @State because subviews of a ForEach would very often cause an edit to the model that supplied the array of that ForEach, among other cases that caused @State to get obliterated. Environment and ObservableObjects became our goto. Were we doing it wrong?
Maybe I’m remembering it wrong, but I don’t recall seeing at @Bindable discussed in what’s new for SwiftUI session. Is this correct? However, discover observation in SwiftUI session did cover @Bindable along with @Observable and @State. Am I remembering this wrong or was there a reason that @Bindable was not covered in the first session?
Is creating Bindings in a View's body a bad idea?For example I have a 3rd library that I can't control, that provides a state model with username
field and class for events like setUsername(String)
. is it ok to do@StateObject var viewModel = MyViewModel()...TextField("", text: .init(get: { viewModel.state.username }, set: { viewModel.events.setUsername($0) })where MyViewModel.state is @Published field.What would be the best way to go about this?
What is the best way to use State and Binding mixed in a child view? For example, if I pass a binding value in initializer, the view must use it. If binding value is nil, the view must create a state and use it. I created a property wrapper for this, and it works. But actually I didn't like it at all. I want to know if there is a better solution for this.