我试图在 swiftui 中构建视图时实现一些多态性:
像这样的东西:
protocol Builder {
func viewForItem() -> View
}
extension ItemPhoto: Builder {
public func viewForItem() -> View {
Image("image.png")
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用associatedtype我有以下问题
protocol Builder {
associatedtype T
func viewForItem() -> T
}
extension ItemPhoto: Builder {
typealias T = Image
public func viewForItem() -> Image {
Image("image.png").scaledToFit()
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想做任何视图构建,我会收到错误
Cannot convert return expression of type 'some View' to return type 'Image'
Run Code Online (Sandbox Code Playgroud)
这是一个解决方案。
protocol Builder {
associatedtype T: View
@ViewBuilder func buildView() -> T
}
Run Code Online (Sandbox Code Playgroud)
protocol Builder {
associatedtype T:View // << not exact, but just a View !!
func viewForItem() -> T
}
struct ItemPhoto { // << just for testing
}
extension ItemPhoto: Builder {
public func viewForItem() -> some View { // opaque !!
Image("image.png").scaledToFit()
}
}
Run Code Online (Sandbox Code Playgroud)