I'd like to declare generic protocols similar to the following:
protocol Factory {
func createWidget<T, TWidget>(_ t: T) -> TWidget
where TWidget: Widget, TWidget.T == T
}
protocol Widget {
associatedtype T
func get() -> T
}
I'm hoping that I can implement concrete variations of Factory
returning their own concrete and opaque Widget
with a hidden implementation.
Here's an example implementation that fails to build:
struct ConcreteFactory: Factory {
func createWidget<T, TWidget>(_ t: T) -> TWidget
where TWidget: Widget, TWidget.T == T {
// This line has an error…
return ConcreteWidget(widgetValue: t)
}
}
struct ConcreteWidget<T>: Widget {
let widgetValue: T
init(widgetValue: T) {
self.widgetValue = widgetValue
}
func get() -> T {
return widgetValue
}
}
However, this does not compile.
At the line indicated, Swift's compiler give the error "Cannot convert return expression of type 'ConcreteWidget' to return type 'TWidget'".
I also tried having ConcreteFactory
return a ConcreteWidget
, but then the error is that ConcreteFactory
doesn't conform to Factory
.