具有方法返回类型 View 的协议

Pav*_*lov 1 ios swift swiftui

我试图在 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)

Asp*_*eri 5

这是一个解决方案。

更新:Xcode 13.4 - 现在我建议

protocol Builder {
    associatedtype T: View
    @ViewBuilder func buildView() -> T
}
Run Code Online (Sandbox Code Playgroud)

原始:使用 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()
    }
}
Run Code Online (Sandbox Code Playgroud)