Swift 协议的通用实现抛出错误“类型不符合协议”

Swift Generic Implementation of protocol throws error `Type does not conform to protocol`

我有 3 个型号 类:

protocol IncludedItem {
    var id: Int { get }
    var text: String { get }
}
protocol PrimaryItem {
    associatedtype Included: IncludedItem

    var id: Int { get }
    var canClose: Bool { get }
    var canDelete: Bool { get }
    var canSend: Bool { get }
    var includedItems: [Included] { get }
}
protocol QuoteItem {
    var id: Int { get }
    var isSelectable: Bool { get }
}

那我想用工厂模式来创建Item。这是我的工厂协议:

protocol QuoteItemFactory {
    associatedtype Item: PrimaryItem

    var delegate: QuoteItemFactoryDelegate? { get set }

    func create(item: Item) -> QuoteItem
}

这是工厂协议的实现:

class OrderQuoteItemFactory: QuoteItemFactory {

    weak var delegate: QuoteItemFactoryDelegate?

    func create<Item: PrimaryItem>(item: Item) -> QuoteItem {
        let viewModel = OrderQuoteViewModel(quote: item)
        viewModel.delegate = self

        return DefaultQuoteItem.quote(id: item.id, viewModel: viewModel)
    }
}

但是我总是得到以下错误: Type 'OrderQuoteItemFactory' does not conform to protocol 'QuoteItemFactory'.

我做错了什么?我知道如果我这样使用它:

class OrderQuoteItemFactory<Item: PrimaryItem>: QuoteItemFactory {

    weak var delegate: QuoteItemFactoryDelegate?

    func create(item: Item) -> QuoteItem {
        let viewModel = OrderQuoteViewModel(quote: item)
        viewModel.delegate = self

        return DefaultQuoteItem.quote(id: item.id, viewModel: viewModel)
    }
}

我知道像这样使用它会很完美。但是我想知道为什么我不能在函数声明中使用泛型。

如果您将工厂协议更改为此会怎么样?

protocol QuoteItemFactory {

    var delegate: QuoteItemFactoryDelegate? { get set }

    func create<Item: PrimaryItem>(item: Item) -> QuoteItem

}

我注意到(至少从你的例子中)你并不真的需要一个 associatedType,所以你可以让函数本身成为通用的,而不是协议。