【问题标题】:Cannot invoke 'decode' with an argument list of type '(Decodable, from: Data)'无法使用类型为“(可解码,来自:数据)”的参数列表调用“解码”
【发布时间】:2019-06-15 21:06:20
【问题描述】:

我在 Playground 中有以下示例代码。如果结果符合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())

非常感谢任何输入!

【问题讨论】:

    标签: swift generics associated-types jsondecoder


    【解决方案1】:

    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 实例有什么意义?

    【讨论】:

    • 感谢您的快速回答。从空数据解码没有意义,这只是 Playground 中的概念证明。我不想添加类型约束的原因是因为我希望某些请求具有不可解码的结果类型。有什么办法吗?
    • @BalázsVincze 您应该重载execute(request:) 以拥有一个专门用于不符合Decodable 的版本T.Result
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2018-11-30
    相关资源
    最近更新 更多