[英]How do I conform to a protocol with associatedtype in Swift?
真是可惜,我真的不知道。 我有一個由其他人開發的項目,它正在使用TRON庫。
我的問題很簡單。 我如何符合具有associatedtype
的協議。 我知道如何編寫協議並遵守該協議,就像使用UITableViewDataSource
和UITableViewDelegate
。
這是TRON協議的代碼:
序列化器
import Foundation
import Alamofire
/// The type in which all data and upload response serializers must conform to in order to serialize a response.
public protocol ErrorHandlingDataResponseSerializerProtocol : DataResponseSerializerProtocol {
/// The type of serialized object to be created by this `ErrorHandlingDataResponseSerializerProtocol`.
associatedtype SerializedError
/// A closure used by response handlers that takes a parsed result, request, response, data and error and returns a serialized error.
var serializeError: (Alamofire.Result<SerializedObject>?,URLRequest?, HTTPURLResponse?, Data?, Error?) -> APIError<SerializedError> { get }
}
我正在嘗試遵循這樣的協議:
class CustomErrorHandlingSerializer: ErrorHandlingDataResponseSerializerProtocol {
}
我需要遵守這一點,因為這里有一個需要ErrorHandlingDataResponseSerializerProtocol
的函數,
我嘗試閱讀圖書館的文檔甚至他們的遷移指南。 原因可能是他們確實沒有關於用法的簡單示例,或者我只是不了解他們的文檔。
您需要指定serializeError
屬性將返回的對象類型。 有兩種方法可以做到這一點:
定義類的SerializedError
子類型,或:
使用typealias
將SerializedError
指向您的serializeError
屬性將提供的適當類型。
TRON作者在這里。
大多數時候,您不需要實現此協議,因為如果模型是JSONDecodable或Codable,則默認情況下會提供responseSerializer。 我假設您使用的是舊版本的TRON和SwiftyJSON,在這種情況下,您可能需要以這種方式調用請求:
let request : APIRequest<...,...> = tron.swiftyJSON.request("path")
如果你真的要實現自定義的響應串,你基本上需要實現兩個協議- ErrorHandlingDataResponseSerializerProtocol
和DataResponseSerializerProtocol
,其中都包含一個associatedtype和變量。
您可以使用typealias,但是最好讓Swift從變量簽名中推斷associatedtype。 您可以查看Response Serializers文檔以供參考,我將其更新為最新語法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.