我在一个游乐场中有以下示例代码。如果网络请求的结果符合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())
任何意见都是非常感谢的!
发布于 2019-01-22 19:46:06
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实例有什么意义?
https://stackoverflow.com/questions/54307524
复制相似问题