如何在 Swift 中遵守具有 associatedtype 的协议?

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

很遗憾,我真的不知道这个。我有这个由其他人开发的项目,它使用 TRON library.

我的问题很简单。我如何遵守带有 associatedtype 的协议。我知道如何编写协议并遵守它,就像 UITableViewDataSourceUITableViewDelegate.

波场协议代码如下:

Serializer.swift

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. 定义 class 的 SerializedError 子类型,或者:

  2. 使用 typealiasSerializedError 指向您的 serializeError 属性 将提供的适当类型。

这里是 TRON 作者。

大多数情况下您不需要实现此协议,因为如果您的模型是 JSONDecodable 或 Codable,则默认会提供 responseSerializer。我假设您使用的是带有 SwiftyJSON 的旧版 TRON,在这种情况下,您可能需要以这种方式调用请求:

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

如果您真的想实现自定义响应序列化程序,您基本上需要实现两个协议 - ErrorHandlingDataResponseSerializerProtocolDataResponseSerializerProtocol,它们都包含一个关联类型和一个变量。

您可以使用 typealias,但最好让 Swift 从变量签名中推断关联类型。你可以看看Response Serializers doc作为参考,我把它更新到最新的语法。