[英]How to declare a generic protocol property requirement in a protocol
經過一段時間的努力,如果您能對此有所了解,將會非常有幫助:
我有一個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>
}
我該如何實現?
在此當前實現中,這會導致錯誤Protocol 'DataParserProtocol' can only be used as a generic constraint because it has Self or associated type requirements
。
提前致謝
ANKIT
如果協議使用Self
或相關類型要求(同質協議),我們可能會注意到將該協議用作具體類型。
因此,而不是使用的DataParserProtocol
作為具體類型的dataParser
屬性(在blueprinted APIWorkerProtocol
),你可以添加一個associatedtype
typeholder,說DataParser
,到APIWorkerProtocol
,這是受限於符合該類型 DataParserProtocol
。
另外,我不確定使用Self.ResultType
作為callAPI(...)
的完成處理程序中的專業化的意圖是什么(因為Self
指的是實現APIWorkerProtocol
的類型;該協議沒有設計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>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.