我正在尝试在swiftui的构建视图中实现某种多态性:
类似这样的东西:
protocol Builder {
func viewForItem() -> View
}
extension ItemPhoto: Builder {
public func viewForItem() -> View {
Image("image.png")
}
}
我收到错误:
Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
如果我尝试使用associatedtype
,则会遇到以下问题
protocol Builder {
associatedtype T
func viewForItem() -> T
}
extension ItemPhoto: Builder {
typealias T = Image
public func viewForItem() -> Image {
Image("image.png").scaledToFit()
}
}
如果我要进行任何视图构建,都会收到错误
Cannot convert return expression of type 'some View' to return type 'Image'
答案 0 :(得分:3)
这是一个解决方案。使用Xcode 11.4 / iOS 13.4进行了测试
x509