Ank*_*han 2 generics protocols ios swift
挣扎了一段时间,如果你能阐明这一点,那将会非常有帮助:
我有一个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>
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这个目标?
在当前的实现中,这会导致错误Protocol 'DataParserProtocol' can only be used as a generic constraint because it has Self or associated type requirements。
提前致谢
安基特
如果协议利用Self或关联类型要求(同质协议),我们可能会注意到将该协议用作具体类型。
因此,您可以将类型持有者(例如 )添加到,而不是使用DataParserProtocol作为属性的具体类型dataParser(在 中绘制) ,该类型仅限于符合 的类型。APIWorkerProtocolassociatedtypeDataParserAPIWorkerProtocolDataParserProtocol
另外,我不确定Self.ResultType在 的 完成处理程序中使用 as 专业化的意图callAPI(...)是什么(因为Self将引用实现APIWorkerProtocol; 的协议的类型 no associatedtype ResultType):您的意思是使用该ResultType类型DataParserProtocol吗?
例如
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>
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2613 次 |
| 最近记录: |