使用 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)
这运行良好,没有问题.
This works well and without issues.
但是,我试图获得一个函数,它只接受 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
}
这会导致以下错误:
无法使用类型为(Encodable)"的参数列表调用encode"
Cannot invoke 'encode' with an argument list of type '(Encodable)'
看encode函数的定义,好像应该可以接受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屋!