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