Cannot invoke 'decode' with an argument list of type '(Decodable, from: Data)'

孤街浪徒 提交于 2019-12-13 04:39:47

问题


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())
    }
}

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!


回答1:


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())
}

Btw what's the point of trying to decode an empty Data instance?



来源:https://stackoverflow.com/questions/54307524/cannot-invoke-decode-with-an-argument-list-of-type-decodable-from-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!