简体   繁体   中英

Protocol that has method return type View

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.

Update: Xcode 13.4 - now I would propose

protocol Builder {
    associatedtype T: View
    @ViewBuilder func buildView() -> T
}

Original: Tested with Xcode 11.4 / iOS 13.4

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()
    }
}

backup

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM