Swift 4-无法使用类型为((Codable)'的参数列表调用'encode'
我构建了一组API函数,这些函数对对象进行编码(使用符合Codable
的Struct
),然后将生成的JSON Data对象发布到服务器,然后对JSON响应进行解码.一切正常-尤其是对Swift 4.2中用于JSON解析的新方法感到满意.但是,现在我想重构代码,以便可以将代码重用于各种方法调用-当我这样做时,我会得到一个非常烦人的错误.
I have built a set of API functions which encode an object (using a Struct
which conforms to Codable
), then Posts the resulting JSON Data object to a server, then decodes the JSON response. All works fine - especially happy with the new method for JSON parsing in Swift 4.2. However, now I want to refactor the code so that I can reuse the code for various method calls - when I do I get a really annoying error.
func encodeRequestJSON(apiRequestObject: Codable) -> Data {
do {
let encoder = JSONEncoder()
let jsonData = try encoder.encode(apiRequestObject)
let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString)
} catch {
print("Unexpected error")
}
return jsonData!
}
这是错误消息:
Cannot invoke 'encode' with an argument list of type '(Codable)'
我尝试将类型从Codable更改为Encodable,但除消息中的类型为(Encodable)以外,都收到相同的错误.有什么建议吗?我的后备方法是在当前ViewController中对数据进行编码,然后调用HTTPPost函数,然后在VC中进行解码.但这确实很笨拙.
I have tried changing the type from Codable, to Encodable but get the same error, except with type (Encodable) in the message. Any advice? My fall-back is to encode the data in the current ViewController, then call the HTTPPost function and then decode back in the VC. But that's really clunky.
您需要将具体类型传递给JSONEncoder.encode
,因此您需要在Encodable
(Codable
不需要,因为它太严格了.)
You need a concrete type to be passed into JSONEncoder.encode
, so you need to make your function generic with a type constraint on Encodable
(Codable
is not needed, its too restrictive).
func encodeRequestJSON<T:Encodable>(apiRequestObject: T) throws -> Data {
return try JSONEncoder().encode(apiRequestObject)
}