我在操场上有以下示例代码。如果网络请求的结果符合Decodable
协议,我想解码该结果。
知道为什么这段代码不起作用吗?
protocol APIRequest {
associatedtype Result
}
func execute<T: APIRequest>(request: T) {
if let decodableResult = T.Result.self as? Decodable {
try JSONDecoder().decode(decodableResult, from: Data())
}
}
我收到错误Cannot invoke 'decode' with an argument list of type '(Decodable, from: Data)'
在这一行:try JSONDecoder().decode(decodableResult, from: Data())
任何意见都非常感谢!
JSONDecoder.decode(_:from:)
方法需要一个符合Decodable
的具体类型作为其输入参数。您需要向T.Result
添加一个额外的类型约束以使其Decodable
。
func execute<T: APIRequest>(request: T) throws where T.Result: Decodable {
try JSONDecoder().decode(T.Result.self, from: Data())
}
顺便说一句,尝试解码空Data
实例有什么意义?