【问题标题】:Swift make Generic function from JSON requestSwift 从 JSON 请求生成通用函数
【发布时间】:2018-08-08 07:25:46
【问题描述】:

我正在使用 JSONRPCKit 库,所以最终请求包含该请求

let request1 = RPCRequest(params: SomeParams)
let batch1 = batchFactory.create(request1)
let httpRequest1 = MyServiceRequest(batch: batch1)
Session.send(httpRequest1){ result in
    switch result {
    case .success(let auth):
        let gson = JSON(auth)
        print(gson)
    case .failure(let error):
        print("Error: ", error)
    }
}

我必须提出很多这样的要求。所以我想让它通用以继续重用它而不是再次输入所有内容。

你能帮帮我吗?

【问题讨论】:

  • 什么样的请求?其他类型的请求是什么样的?这些的共同点是什么?

标签: json swift function generics request


【解决方案1】:

只需创建一个通用方法,将这些代码包装在类似这样的东西中,

func sendRequest<T>(request: RCPRequest,
                    mapping: @escaping (JSON) throws -> T,
                    completion: @escaping  (T?, Error?) -> Void) {
    let batch = batchFactory.create(request)
    let httpRequest = MyServiceRequest(batch: batch)

    Session.send(httpRequest){ result in
        switch result {
        case .success(let auth):
            let gson = JSON(auth)
            do {
                let output = try mapping(gson)
                completion(output, nil)
            } catch {
                completion(nil, error)
            }
        case .failure(let error):
            completion(nil, error)
        }
    }
}

那就这样称呼吧,

let request1 = RPCRequest(params: SomeParams)
sendRequest(request: request1,
            mapping: { json in
                    // convert from json to the custom type T, whatever T is
                    // throw error if something isnt right in json
            },
            completion: { output, error in
                if let output = output {

                }
            })

【讨论】:

  • 非常感谢您的帮助!有些方面我没看懂。当我在做映射时:“json in”什么自定义类型“T”应该转换 JSON。你能举个简单的场景例子吗
猜你喜欢
  • 2020-10-12
  • 2018-06-29
  • 2012-07-06
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
相关资源
最近更新 更多