[英]How can I pass nil to generic type parameter on Swift?
I'm using Alamofire5 and Swift 5.7.x.我正在使用 Alamofire5 和 Swift 5.7.x。
There is a problem when I receive an response data from API server.当我从 API 服务器收到响应数据时出现问题。
The response data default is:响应数据默认为:
{
statusCode: 200
message: "OK"
items: null
}
But the "items" attribute can be anything data type.但是“items”属性可以是任何数据类型。 null, string, int, array, object..
null,字符串,整数,数组,object..
I was about to solve using Generics. But I don't know how to handle the null.我正要解决使用 Generics。但我不知道如何处理 null。
It's API common code:是API 普通码:
struct Response<T: Codable>: Codable {
var statusCode: Int
var message: String
var items: T?
}
class API {
func request<Parameters: Encodable, T: Decodable>(_ path: String,
method: HTTPMethod = .get,
params: Parameters? = nil,
completion: @escaping (Result<Response<T?>, NetworkError>) -> Void) {
//some codes..
AF.request("\(path)",
method: method,
parameters: params,
encoder: JSONParameterEncoder.prettyPrinted
)
.validate(statusCode: 200..<400)
.validate(contentType: ["application/json"])
.responseData { response in
switch response.result {
case .success(let data):
guard let decodedData = try? JSONDecoder().decode(Response<T?>.self, from: data) else { return }
print(decodedData)
completion(.success(decodedData as Response<T?>))
case.failure(let error):
// some codes..
}
}
}
}
It's caller:来电者:
API.shared.request("/users/device", method: .post, params: reqParam) { (response: Result<Response<This is the problem..!!>, NetworkError>) in
switch response {
case .success(let data):
print("userDevice updated")
debugPrint(data)
case .failure(let error):
// some codes..
}
}
How can I pass nil on the caller?我怎样才能将 nil 传递给调用者?
Considering you have following response for all your API requests考虑到您对所有 API 请求都有以下回复
{
statusCode: 200
message: "OK"
items: null
}
And your Codable struct as following你的 Codable 结构如下
struct Response<T: Codable>: Codable {
var statusCode: Int
var message: String
var items: T? // Notice this is declared as Optional
}
As your items variable is declared as optional it will work as expected with little change.由于您的 items 变量被声明为可选,因此它将按预期工作,几乎没有变化。
You can declare an Empty Struct which can be used when you are expecting null
value for items
key, like following.您可以声明一个 Empty Struct,当您期望
items
键的值为null
时可以使用它,如下所示。
struct EmptyResponse: Codable {
}
You can use EmptyResponse
struct as following:您可以按如下方式使用
EmptyResponse
结构:
API.shared.request("/users/device", method: .post, params: reqParam) { (response: Result<Response<EmptyResponse>, NetworkError>) in
switch response {
case .success(let data):
debugPrint(data)
if let items = data.items {
// Use items here
} else {
// Items is nil
}
case .failure(let error):
// some codes..
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.