方法返回类型为View的协议

时间:2020-05-03 12:59:54

标签: ios swift swiftui

我正在尝试在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'

1 个答案:

答案 0 :(得分:3)

这是一个解决方案。使用Xcode 11.4 / iOS 13.4进行了测试

x509