无法使用类型为“(可解码,来自:数据)"的参数列表调用“解码" [英] Cannot invoke 'decode' with an argument list of type '(Decodable, from: Data)'
问题描述
我在操场上有以下示例代码.如果网络请求的结果符合Decodable
协议,我想对该结果进行解码.
I have the following example code in a Playground. I want to decode the result of a network request if that result conforms to the Decodable
protocol.
您知道为什么此代码不起作用吗?
Any idea why this code does not work?
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())
I am getting the error Cannot invoke 'decode' with an argument list of type '(Decodable, from: Data)'
on this line: try JSONDecoder().decode(decodableResult, from: Data())
任何输入都将不胜感激!
Any input is greatly appreciated!
推荐答案
JSONDecoder.decode(_:from:)
方法需要符合Decodable
的具体类型作为其输入参数.您需要向T.Result
添加一个额外的类型约束,以使其成为Decodable
.
The JSONDecoder.decode(_:from:)
method requires a concrete type conforming to Decodable
as its input argument. You need to add an extra type constraint to T.Result
to make it Decodable
.
func execute<T: APIRequest>(request: T) throws where T.Result: Decodable {
try JSONDecoder().decode(T.Result.self, from: Data())
}
顺便说一句,尝试解码一个空的Data
实例有什么意义?
Btw what's the point of trying to decode an empty Data
instance?
这篇关于无法使用类型为“(可解码,来自:数据)"的参数列表调用“解码"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!