How to Use Swift @Bindable with Observable Protocol
We can conform a protocol to Observation.Observable by conforming it to AnyObject and Observable.
This won't automatically make all of it's implementations observable, but makes it possible to use things like @Bindable by satisfying the compiler.
@MainActor
protocol StoreProtocol: AnyObject, Observable {}
In our implementation we need to explicitly use the @Observation protocol to add observation to our class. Without this our code will compile, but observation won't work.
@Observable
final class MyStore: StoreProtocol {}
We then can use the protocol via generics in our view and use the @Bindable keyword.
struct StoreView<Store: StoreProtocol>: View {
@Bindable var store: Store
}
If we use any StoreProtocol instead of a generic we will get the following compiler error:
'init(wrappedValue:)' is unavailable: The wrapped value must be an object that conforms to Observable.