ios - 如何抽象网络模型获取

标签 ios swift generics swift-protocols

我没有将网络模型加载到每个 Controller 中,而是试图将其抽象到一个 Controller 中 ModelLoader

这是我到目前为止的想法:

protocol ModelLoaderDelegate: class {
    func didFetch(model: Any)
    func modelFailedToFetch(errorMessage: String)
}

final class ModelLoader<ModelType> {

    let api: API
    weak var delegate: ModelLoaderDelegate?
    private let client = dependencies.client

    init(api: API) {
        self.api = api
    }

    func fetchModel() {
        client.performRequest(api: api, decodeTo: ModelType.self, completion: { result in
            switch result {
            case .success(let value):
                self.delegate?.didFetch(model: value)
            case .failure(let error):
                self.delegate?.modelFailedToFetch(errorMessage: error.localizedDescription)
            }
        })
    }
}

到目前为止,我无法做的一件事是将 ModelLoaderDelegatedidFetch 方法中的 Any 替换为类泛型参数。

我试着这样做:

func didFetch<T>(info: T)

但是在委托(delegate)的实现者中:

func didFetch<T>(info: T) {
 // I need a concerete type here not a generic
}

找不到其他方法。

最佳答案

您可以通过闭包制作逻辑,而不是通过委托(delegate)来完成此操作:

final class ModelLoader<ModelType> {

    let api: API
    private let client = dependencies.client

    init(api: API) {
        self.api = api
    }

    func fetchModel<ModelType>(completion: @escaping (Result<ModelType, Error>) -> ()) {
        client.performRequest(api: api, decodeTo: ModelType.self, completion: { result in
            switch result {
            case .success(let value):
                completion(.success(value))
            case .failure(let error):
                completion(.failure(error))
            }
        })
    }
}

我认为使用这种方法会更容易处理响应:)

关于ios - 如何抽象网络模型获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57653873/

相关文章:

java - Java 编译器如何对下界通配符执行类型删除?

Python:输入一个接收类型并返回该类型实例的通用函数

iOS 在 uitableview 单元格中设置图像宽度

iphone - 分组的 UITableView 中未显示文本

objective-c - xib vs iPhone : distorted,重叠对象

ios - Swift 中带有 UISwitch 状态的 If 语句

json - 如何使用 SwiftyJSON 解析带有 AnyHashable 值的 PayPal JSON 响应?

java - 如何使用泛型在方法中返回不同的类型?

ios - 如何快速检测谷歌地图的相机位置

swift - 在 Swift 中使用容器 View 进行委托(delegate)