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

Ios 如何在协议中声明通用协议属性要求,ios,swift,generics,protocols,Ios,Swift,Generics,Protocols,如果您能了解以下几点,将非常有帮助: 我有一个APIWorkerProtocol,它有一个属性要求,所需的属性是一个协议,即DataParserProtocol protocol APIWorkerProtocol { var apiRequestProvider : APIRequestGeneratorProtocol {get} var dataParser : DataParserProtocol{get} func callAPI(completionHandl

如果您能了解以下几点,将非常有帮助:

我有一个
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>
}
协议APIWorkerProtocol{
var APIRestProvider:APIRestGeneratorProtocol{get}
var dataParser:DataParserProtocol{get}
func callAPI(completionHandler:@escaping(APICallResult)->Void)
}
协议数据解析协议{
associatedtype ExpectedRawDataType
associatedtype结果类型
func parseFetchedData(fetchedData:ExpectedRawDataType)->APICallResult
}
我怎样才能做到这一点

在当前的实现中,这会导致错误
协议“DataParserProtocol”只能用作一般约束,因为它具有自身或关联的类型要求

提前谢谢


Ankit

如果协议使用了
自身
或相关类型要求(同质协议),我们可以注意将协议作为具体类型使用

因此,您可以向
APIWorkerProtocol
添加一个
关联类型
的类型持有者,比如
数据解析器
,而不是使用
数据解析器协议
作为
数据解析器
属性的具体类型(蓝印在
APIWorkerProtocol
中),它被限制为符合
DataParserProtocol
的类型

另外,我不确定使用
Self.ResultType
作为
callAPI(…)
的完成处理程序中的专门化的目的是什么(因为
Self
指的是实现
APIWorkerProtocol
;一个不设计
associatedtype
ResultType
的协议):您的意思是使用
DataParserProtocol
类型的
ResultType

例如

协议APIWorkerProtocol{
associatedtype数据解析器:DataParserProtocol
var dataParser:dataParser{get}
func callAPI(completionHandler:@escaping(APICallResult)->Void)
}
协议数据解析协议{
associatedtype ExpectedRawDataType
associatedtype结果类型
func parseFetchedData(fetchedData:ExpectedRawDataType)->APICallResult
}

如果协议使用了
自身
或相关类型要求(同质协议),我们可以注意将协议作为具体类型使用

因此,您可以向
APIWorkerProtocol
添加一个
关联类型
的类型持有者,比如
数据解析器
,而不是使用
数据解析器协议
作为
数据解析器
属性的具体类型(蓝印在
APIWorkerProtocol
中),它被限制为符合
DataParserProtocol
的类型

另外,我不确定使用
Self.ResultType
作为
callAPI(…)
的完成处理程序中的专门化的目的是什么(因为
Self
指的是实现
APIWorkerProtocol
;一个不设计
associatedtype
ResultType
的协议):您的意思是使用
DataParserProtocol
类型的
ResultType

例如

协议APIWorkerProtocol{
associatedtype数据解析器:DataParserProtocol
var dataParser:dataParser{get}
func callAPI(completionHandler:@escaping(APICallResult)->Void)
}
协议数据解析协议{
associatedtype ExpectedRawDataType
associatedtype结果类型
func parseFetchedData(fetchedData:ExpectedRawDataType)->APICallResult
}
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>
}