如何在Swift中符合具有关联类型的协议?

时间:2017-12-07 03:43:01

标签: swift swift-protocols

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

我的问题很简单。如何使用associatedtype符合协议。我知道如何编写协议并遵守它,就像使用UITableViewDataSourceUITableViewDelegate一样。

以下是TRON协议的代码:

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

的函数

enter image description here

我试过阅读图书馆的文档,甚至是他们的迁移指南。要么他们真的没有关于他们使用的直接例子,要么我不理解他们的文档。

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

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

2 个答案:

答案 0 :(得分:1)

您需要指定serializeError属性将返回的对象类型。有两种方法可以做到:

  1. 定义班级的SerializedError子类型,或者:

  2. 使用typealiasSerializedError指向您的serializeError媒体资源所提供的相应类型。

答案 1 :(得分:1)

TRON作者在这里。

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

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

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

您可以使用typealias,但让Swift从变量签名推断出associatedtype更好。您可以查看Response Serializers doc作为参考,我将其更新为最新语法。