I am trying to achieve some polymorphism in building views in swiftui:
Something like this:
protocol Builder {
func viewForItem() -> View
}
extension ItemPhoto: Builder {
public func viewForItem() -> View {
Image("image.png")
}
}
I receive error:
Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
If I try to use associatedtype
I have following problem
protocol Builder {
associatedtype T
func viewForItem() -> T
}
extension ItemPhoto: Builder {
typealias T = Image
public func viewForItem() -> Image {
Image("image.png").scaledToFit()
}
}
If I want to do any view building I receive error
Cannot convert return expression of type 'some View' to return type 'Image'
Here is a solution.
protocol Builder {
associatedtype T: View
@ViewBuilder func buildView() -> T
}
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()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.