I'm trying to figure out why this happens:
protocol WidgetRepresentable {
associatedtype W: Widget
func widgetFor<Value>(keypath: KeyPath<Self, Value>) -> W
}
// 1. Then, this works
struct SomeModel: WidgetRepresentable {
func widgetFor<Value>(keypath: KeyPath<Self, Value>) -> SliderWidget<Float> {
SliderWidget(from: 0, to: 1)
}
}
// 2. While this doesn't
// error: Type 'SomeModel' does not conform to protocol 'WidgetRepresentable'
struct SomeModel: WidgetRepresentable {
func widgetFor<Value>(keypath: KeyPath<Self, Value>) -> some Widget {
SliderWidget(from: 0, to: 1)
}
}
Yet, remove the generic parameter and everything works again:
protocol WidgetRepresentable {
associatedtype W: Widget
func widgetWith(name: String) -> W
}
struct SomeModel: WidgetRepresentable {
func widgetWith(name: String) -> some Widget {
SliderWidget(from: 0, to: 1)
}
}
It's like you either have a generic parameter or an opaque return value, but never both. However, some Widget
should be resolved to SliderWidget
before deciding the return type in the second case, which means it should work as the first case does (?).