gpt4 book ai didi

json - Swift 从 JSON 请求生成通用函数

转载 作者:行者123 更新时间:2023-11-28 14:24:04 24 4
gpt4 key购买 nike

我正在使用 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)
}
}

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

你能帮帮我吗?

最佳答案

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

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 - Swift 从 JSON 请求生成通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51740840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com