I would like to declare an @EnvironmentObject as a protocol, namely as
where Authenticator is
However, when I add this to the environment as
the compiler throws an error at:
Is this even a good idea? If so, what am I doing wrong?
^
Code Block protocol AccessTokenProvider: Authenticator { func accessToken() -> AccessTokenPublisher }
where Authenticator is
Code Block public class Authenticator: NSObject, ObservableObject
However, when I add this to the environment as
Code Block var authenticator: AccessTokenProvider = MyAuthenticator() […] ContentView().environmentObject(authenticator)
the compiler throws an error at:
Code Block struct ContentView: View { // error: property type 'AccessTokenProvider' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject' @EnvironmentObject var authenticator: AccessTokenProvider ^
Is this even a good idea? If so, what am I doing wrong?
^
The type of @EnvirontmentObject must conform to ObservableObject.what am I doing wrong?
But, in Swift, usual protocols used as type cannot conform to any protocols.
(In your declaration of AccessTokenProvider, : Authenticator works as a requirement of the protocol, but it does not mean AccessTokenProvider conforming to ObservableObject.)
Under the current restriction of the type system of Swift, you cannot use protocol type for @EnvirontmentObject.
You can start some discussion about this in forums.swift.org .