如何在协议中声明通用协议属性要求 [英] How to declare a generic protocol property requirement in a protocol

查看:55
本文介绍了如何在协议中声明通用协议属性要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

苦苦挣扎一段时间,如果您能对此有所了解,将会很有帮助:

Struggling for a while with, it will be really helpful if you can shed some light on this:

我有一个具有属性要求的 APIWorkerProtocol ,必需的属性是协议,即 DataParserProtocol

I have an APIWorkerProtocol which has a property requirement, the required property is a protocol i.e 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>
}

我该如何实现?

在当前的实现中,这会导致错误 Protocol'DataParserProtocol'只能用作通用约束,因为它具有Self或关联的类型要求.

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.

预先感谢

Ankit

推荐答案

如果协议使用 Self 或关联的类型要求(同质协议),我们可能会注意到将该协议用作具体的类型.

If a protocol make use of Self or associated type requirements (a homogenous protocol), we may note use the protocol as a concrete type.

因此,除了使用 DataParserProtocol 作为 dataParser 属性的具体类型(在 APIWorkerProtocol 中绘制)外,您可以添加<将code> associatedtype 类型持有者(例如 DataParser )绑定到 APIWorkerProtocol ,而则将其约束为符合 DataParserProtocol 的类型.

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.

此外,我不确定在 callAPI(...)的完成处理程序中使用 Self.ResultType 作为专门化的意图是什么(因为自我"是指实现 APIWorkerProtocol 的类型;该协议没有将 associatedtype ResultType 进行蓝图):您是要使用吗? DataParserProtocol 类型的 ResultType ?

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?

例如

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

这篇关于如何在协议中声明通用协议属性要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆