简体   繁体   English

如何在协议中声明通用协议属性要求

[英]How to declare a generic protocol property requirement in a protocol

Struggling for a while with, it will be really helpful if you can shed some light on this: 经过一段时间的努力,如果您能对此有所了解,将会非常有帮助:

I have an APIWorkerProtocol which has a property requirement, the required property is a protocol ie DataParserProtocol 我有一个APIWorkerProtocol ,它具有一个属性要求,所需的属性是一个协议,即DataParserProtocol

protocol APIWorkerProtocol {
    var apiRequestProvider : APIRequestGeneratorProtocol {get}
    var dataParser : DataParserProtocol{get}
    func callAPI(completionHandler: @escaping (APICallResult<Self.ResultType>) -> Void)
}

protocol DataParserProtocol {
    associatedtype ExpectedRawDataType
    associatedtype ResultType
    func parseFetchedData(fetchedData : ExpectedRawDataType) -> APICallResult<ResultType>
}

How can I achieve this? 我该如何实现?

In this current implementation, this causes an error Protocol 'DataParserProtocol' can only be used as a generic constraint because it has Self or associated type requirements . 在此当前实现中,这会导致错误Protocol 'DataParserProtocol' can only be used as a generic constraint because it has Self or associated type requirements

Thanks in advance 提前致谢

Ankit ANKIT

If a protocol make use of Self or associated type requirements (a homogenous protocol), we may note use the protocol as a concrete type. 如果协议使用Self或相关类型要求(同质协议),我们可能会注意到将该协议用作具体类型。

So instead of using the DataParserProtocol as the concrete type of the dataParser property (blueprinted in the APIWorkerProtocol ), you could add an associatedtype typeholder, say DataParser , to the APIWorkerProtocol , which is constrained to types that conform to the DataParserProtocol . 因此,而不是使用的DataParserProtocol作为具体类型的dataParser属性(在blueprinted APIWorkerProtocol ),你可以添加一个associatedtype typeholder,说DataParser ,到APIWorkerProtocol ,这是受限于符合类型 DataParserProtocol

Also, I'm not sure what the intent with using Self.ResultType as specialization in the completion handler of callAPI(...) is (since Self would refer to the type implementing the APIWorkerProtocol ; a protocol which blueprints no associatedtype ResultType ): did you mean to use the ResultType of the DataParserProtocol type? 另外,我不确定使用Self.ResultType作为callAPI(...)的完成处理程序中的专业化的意图是什么(因为Self指的是实现APIWorkerProtocol的类型;该协议没有设计associatedtype ResultType蓝图):您的意思是使用ResultType中的DataParserProtocol类型?

Eg 例如

protocol APIWorkerProtocol {
    associatedtype DataParser: DataParserProtocol
    var dataParser : DataParser { get }
    func callAPI(completionHandler: @escaping (APICallResult<DataParser.ResultType>) -> Void)
}

protocol DataParserProtocol {
    associatedtype ExpectedRawDataType
    associatedtype ResultType
    func parseFetchedData(fetchedData: ExpectedRawDataType) -> APICallResult<ResultType>
}

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

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