Swift从JSON请求中生成通用函数

时间:2018-08-08 07:25:46

标签: json swift function generics request

我正在使用JSONRPCKit lib,因此最终请求包含该请求

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)
    }
}

我必须提出很多这样的要求。因此,我想使其通用,以保持重用,而不必再次键入所有内容。

能帮我吗?

1 个答案:

答案 0 :(得分: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 {

                }
            })