簡體   English   中英

如何在協議中聲明通用協議屬性要求

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM