问题
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