簡體   English   中英

如何在Swift中符合與associatedtype的協議?

[英]How do I conform to a protocol with associatedtype in Swift?

真是可惜,我真的不知道。 我有一個由其他人開發的項目,它正在使用TRON庫。

我的問題很簡單。 我如何符合具有associatedtype的協議。 我知道如何編寫協議並遵守該協議,就像使用UITableViewDataSourceUITableViewDelegate

這是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的函數,

在此處輸入圖片說明

我嘗試閱讀圖書館的文檔甚至他們的遷移指南。 原因可能是他們確實沒有關於用法的簡單示例,或者我只是不了解他們的文檔。

  1. https://github.com/MLSDev/TRON/blob/master/Docs/4.0%20Migration%20Guide.md

  2. https://github.com/MLSDev/TRON

您需要指定serializeError屬性將返回的對象類型。 有兩種方法可以做到這一點:

  1. 定義類的SerializedError子類型,或:

  2. 使用typealiasSerializedError指向您的serializeError屬性將提供的適當類型。

TRON作者在這里。

大多數時候,您不需要實現此協議,因為如果模型是JSONDecodable或Codable,則默認情況下會提供responseSerializer。 我假設您使用的是舊版本的TRON和SwiftyJSON,在這種情況下,您可能需要以這種方式調用請求:

let request : APIRequest<...,...> = tron.swiftyJSON.request("path")

如果你真的要實現自定義的響應串,你基本上需要實現兩個協議- ErrorHandlingDataResponseSerializerProtocolDataResponseSerializerProtocol ,其中都包含一個associatedtype和變量。

您可以使用typealias,但是最好讓Swift從變量簽名中推斷associatedtype。 您可以查看Response Serializers文檔以供參考,我將其更新為最新語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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