使用JSONEncoder以Codable作为类型对变量进行编码 [英] Using JSONEncoder to encode a variable with Codable as type
问题描述
我设法让JSON和plist编码和解码都能正常工作,但只能直接调用特定对象上的编码/解码函数。
I managed to get both JSON and plist encoding and decoding working, but only by directly calling the encode/decode function on a specific object.
例如:
struct Test: Codable {
var someString: String?
}
let testItem = Test()
testItem.someString = "abc"
let result = try JSONEncoder().encode(testItem)
这很有效且无问题。
但是,我试图获得一个只接受 Codable
协议一致性的函数作为类型并保存该对象。
However, I am trying to get a function that takes in only the Codable
protocol conformance as type and saves that object.
func saveObject(_ object: Encodable, at location: String) {
// Some code
let data = try JSONEncoder().encode(object)
// Some more code
}
这会导致以下错误:
无法使用类型为'(可编码)'的参数列表调用'encode'
Cannot invoke 'encode' with an argument list of type '(Encodable)'
查看编码函数的定义,好像它应该能够接受 Encodable
,除非 Value
是一些我不知道的奇怪类型。
Looking at the definition of the encode function, it seems as if it should be able to accept Encodable
, unless Value
is some strange type I don't know of.
open func encode<Value>(_ value: Value) throws -> Data where Value : Encodable
推荐答案
使用约束的泛型类型 Encodable
func saveObject<T : Encodable>(_ object: T, at location: String) {
//Some code
let data = try JSONEncoder().encode(object)
//Some more code
}
这篇关于使用JSONEncoder以Codable作为类型对变量进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!