简体   繁体   English

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

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

I have 3 model classes:我有 3 个 model 类:

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 }
}

Then I want to use the factory pattern for Item creation.然后我想使用工厂模式来创建项目。 This is my factory protocol:这是我的工厂协议:

protocol QuoteItemFactory {
    associatedtype Item: PrimaryItem

    var delegate: QuoteItemFactoryDelegate? { get set }

    func create(item: Item) -> QuoteItem
}

And this is an implementation of the factory protocol:这是工厂协议的实现:

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)
    }
}

But then I always get the following error: Type 'OrderQuoteItemFactory' does not conform to protocol 'QuoteItemFactory' .但后来我总是收到以下错误: Type 'OrderQuoteItemFactory' does not conform to protocol 'QuoteItemFactory'

What am I doing wrong?我究竟做错了什么? I know if I use it like this:我知道我是否像这样使用它:

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)
    }
}

I know that using it like this will work perfectly.我知道像这样使用它会很完美。 But I'm wondering why I can't use the generic with the function declaration.但我想知道为什么我不能将泛型与 function 声明一起使用。

What if you change your factory protocol to this?如果您将工厂协议更改为此怎么办?

protocol QuoteItemFactory {

    var delegate: QuoteItemFactoryDelegate? { get set }

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

}

I noticed (at least from your example) that you don't really need an associatedType , so you could just make the function itself generic, instead of the protocol.我注意到(至少从您的示例中)您实际上并不需要associatedType ,因此您可以将 function 本身设为通用,而不是协议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM