swift - 通用可解码,无需解码
问题描述
我正在使用通用方法来解码 AlamoFire 生成的 JSONresponse。我的功能如下:
private func fetch<T: Swift.Decodable>(URLRequest: URLRequestConvertible) -> SignalProducer<T, NetworkError> {
return Network.request(URLRequest)
.attemptMap { JSON in
do {
let jsondata = try JSONSerialization.data(withJSONObject: JSON as! [String:Any], options: .prettyPrinted)
return .success(try JSONDecoder().decode(T.self, from: jsondata))
} catch let error {
Logger.shared.error("Error while decoding a JSON", error: error as NSError, userInfo: ["json" : JSON, "urlRequest" : URLRequest.urlRequest!.debugDescription])
return .failure(.incorrectDataReturned)
}
}
}
对于我的每个请求,我都创建了一个遵循可解码协议的结构。
对于一个请求,我不想解码 JSON,因为它的结构很复杂,而且我只需要在另一个请求中将它发送回来,我只想将响应保存在一个结构中,例如这样的一个:
struct GenericResponse: Swift.Decodable {
let data: Data
}
其中数据是响应。因此,我只想获取响应并将其放入结构中,而无需进一步解码。
是否有可能不破坏我的功能的通用性?如果 T.self 属于某种类型,他们是否可以构建不解码的解码器?
解决方案
如果要避免对特定响应进行解码,可以重载该fetch
函数来处理这种情况。
请参阅以下示例,其中第二次提取method
被重载以将响应数据保存在结构中,而不是通过解码过程。
typealias JSON = [String: Any]
protocol RawResponse {
init(data: Data)
}
// 1
func fetch<T: Decodable>(json: JSON) -> T? {
guard let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []),
let response = try? JSONDecoder().decode(T.self, from: jsonData) else {
return nil
}
return response
}
// 2
func fetch<T: RawResponse>(json: JSON) -> T? {
guard let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []) else {
return nil
}
return T(data: jsonData)
}
有了这个重载,如果响应struct
符合RawResponse
而不是Decodable
(因为我们不需要实际解码数据),fetch
就会触发重载。
struct UserResponse: Decodable {
var username: String
}
let userJson: JSON = [
"username": "someUser"
]
let user: UserResponse? = fetch(json: userJson) // call fetch #1
user?.username // someUser
struct GenericResponse: RawResponse {
var data: Data
}
let notParsable: JSON = [
"someKey": "someValue"
]
let rawData: GenericResponse? = fetch(json: notParsable) // call fetch #2
rawData?.data // 23 bytes
推荐阅读
- scala - 将 Iterator 映射到 Iterator[Future] 的行为不符合预期
- java - 搜索中出现的不在类路径中的额外文件
- java - 为什么我会使用此代码获得 IllegalMonitorStateException?
- python - 名称“HTML”未定义
- c - 使用循环在c中绘制一个编号的三角形
- javascript - scrollTop = scrollHeight 在聊天机器人中不起作用
- c# - 处理 ASP.NET Core Web API 对象属性绑定
- bash - 如何替换一行中已知位置的未知值?
- excel - Range 类的 Excel VBA AutoFill 方法失败-仅存在一条记录时失败
- vega-lite - 如何在 Vega LIte 中创建相对标记位置