[英]Convert concrete type having generic in class signature swift
I have a struct
like this我有这样的
struct
struct ApiResponse<T: Codable>: Codable {
let result: T?
let statusCode: String?
}
Somewhere in my code I need statusCode
.在我的代码中的某个地方我需要
statusCode
。 I am not interested in result
but Swift is not allowing me to use following:我对
result
不感兴趣,但 Swift 不允许我使用以下内容:
let apiResponse = value as? ApiResponse
it shows following error:它显示以下错误:
Generic parameter 'T' could not be inferred in cast to 'ApiResponse'
无法推断通用参数“T”强制转换为“ApiResponse”
which is quite obvious since struct definition ask some struct conforming to Codable
but at same time i can not use one type as it will fail for other types.这很明显,因为结构定义要求一些符合
Codable
的结构,但同时我不能使用一种类型,因为它对于其他类型会失败。
eg例如
let apiResponse = value as? ApiResponse<ApiResult>
would be true for one type of response but if i have ApiResponse<ApiOtherResult>
it will fail.对于一种类型的响应是正确的,但如果我有
ApiResponse<ApiOtherResult>
它将失败。
NetworkLayer.requestObject(router: router) { (result: NetworkResult<T>) in
switch result {
case .success(let value):
if let apiResponse = value as? ApiResponse {
}
case .failure: break
}
}
I'd suggest adding a new protocol我建议添加一个新协议
protocol StatusCodeProvider {
var statusCode: String? { get }
}
Add it as a requirement in your function making sure that T
in NetworkResult<T>
conforms to StatusCodeProvider
and add conformance for every T
you want to request.将其作为要求添加到您的 function 中,确保
NetworkResult<T>
T
的 T 符合StatusCodeProvider
并为您要请求的每个T
添加符合性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.