无法使用类型为 '(Decodable, from: Data)' 的参数列表调用'decode'



我在操场上有以下示例代码。如果网络请求的结果符合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实例有什么意义?

相关内容

最新更新