I have the following protocol:
protocol ViewCreator {
associatedtype ResultView: View
@ViewBuilder func createView() -> ResultView
}
and I want to get its type, for example to get its name. So I wrote the following code:
let typeName = String(describing: ViewCreator.self)
but got the following error:
Protocol 'ViewCreator' can only be used as a generic constraint because it has Self or associated type requirements.
In this case how can I get "self" of the protocol with the associated type?
P.S. I don't have an implementation of this protocol in scope.
CodePudding user response:
It is no different than when not using an associated type.
(any ViewCreator).self
String(describing: (any ViewCreator).self) // "ViewCreator"
In the future, you may have the option to use primary associated types to provide restrictions. But for now, this will compile and execute, but be considered <<< invalid type >>>
.
protocol ViewCreator<ResultView> {
(any ViewCreator<EmptyView>).self
CodePudding user response:
You need to have an implementation of the protocol in the same scope your protocol is in and then use .self
on that implementation.