为什么我在 swift 中得到 'X is not convertible to T.Y'?

Why am I getting 'X is not convertible to T.Y' in swift?

我收到以下代码片段中的错误 'StreamingModel' is not convertible to '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。

这里:

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 {