为什么我迅速得到“ X不可转换为T.Y”?

时间:2019-10-08 06:47:50

标签: swift protocols swiftui associated-types

在以下代码段中,我收到错误“ StreamingModel”无法转换为“ T.EAModel”。有人可以帮我理解错误。

public struct GraphViewsMainSUI<T> : View where T: GraphViewRepresentableProtocol {

    @ObservedObject public var graphToggle: GraphToggle
    @ObservedObject public var model: StreamingModel

    public var body: some View {
        HStack {
            VStack {
                Text("Select Graphs").font(.headline)
                GroupBox{
                    GraphChecksSUI(toggleSets: $graphToggle.toggleSets)
                }
            }.padding(.trailing, 35)
            T(model: model, toggleSets: $graphToggle.toggleSets)   <<<< COMPILE ERROR HERE
        }.frame(minWidth: 860, idealWidth: 860, maxWidth: .infinity, minHeight: 450, idealHeight: 450, maxHeight: .infinity).padding()
    }
}

public protocol GraphViewRepresentableProtocol: NSViewRepresentable  {

    associatedtype EAModel

    init(model: EAModel, toggleSets: Binding<[GraphToggleSet]>)

}

以下是我用于符合GraphViewRepresentable的T类型的结构。

public struct GraphViewRepresentable: NSViewRepresentable, GraphViewRepresentableProtocol {    

    public var model: StreamingModel
    @Binding public var toggleSets: [GraphToggleSet]

    public init(model: StreamingModel, toggleSets: Binding<[GraphToggleSet]>) {
        self.model = model
        self._toggleSets = toggleSets
    }
    ...
}

在协议中,associatedtype没有限制,因此我不明白为什么编译器未将EAModel类型设置为StreamingModel。

1 个答案:

答案 0 :(得分:1)

这里:

T(model: model, toggleSets: $graphToggle.toggleSets)

您假设T是具有关联类型EAModel == StreamingModel的类型,不一定是正确的。我可以传递这样的类型:

struct Foo : GraphViewRepresentableProtocol {
    typealias EAType = Int
    init(model: EAModel, toggleSets: Binding<[GraphToggleSet]>) { }
}

您的代码将中断。

您可能需要将T限制为具有EAModel == StreamingModel的类型集:

public struct GraphViewsMainSUI<T> : View where T: GraphViewRepresentableProtocol, T.EAModel == StreamingModel {