使用JSON编码器对Codable作为类型的变量进行编码

时间:2022-03-01 16:28:31

I managed to get both JSON and P-list encoding and decoding working, but only by directly calling the encode/decode function on a specific object.

我设法让JSON和P-list编码和解码都工作,但只能通过直接调用特定对象上的编码/解码函数。

For example:

例如:

struct Test: Codable {
    var someString: String?
}

let testItem = Test()
testItem.someString = "abc"

let result = try JSONEncoder().encode(testItem)

This works well and without issues.

这很好,没有问题。

However, I am trying to get a function that takes in only the Codable protocol conformance as type and saves that object.

但是,我试图获得一个只接受Codable协议一致性的函数并保存该对象。

func saveObject(_ object: Encodable, at location: String) {
    //Some code

    let data = try JSONEncoder().encode(object)

    //Some more code
}

This results in the following error:

这会导致以下错误:

Cannot invoke 'encode' with an argument list of type '(Encodable)'

无法使用类型'(Encodable)'的参数列表调用'encode'

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.

看看编码函数的定义,似乎它应该能够接受Encodable,除非Value是一些我不知道的奇怪类型。

    open func encode<Value>(_ value: Value) throws -> Data where Value : Encodable

2 个解决方案

#1


39  

Use a generic type constrained to Encodable

使用约束为Encodable的泛型类型

func saveObject<T : Encodable>(_ object: T, at location: String) {
    //Some code

    let data = try JSONEncoder().encode(object)

    //Some more code
}

#2


0  

You need to use generic function with generic type Encodable

您需要使用通用类型Encodable的泛型函数

You can't

你不能

func toData(object: Encodable) throws -> Data {
  let encoder = JSONEncoder()
  return try encoder.encode(object) // Cannot invoke 'encode' with an argument list of type '(Encodable)'
}

You can

您可以

func toData<T: Encodable>(object: T) throws -> Data {
  let encoder = JSONEncoder()
  return try encoder.encode(object)
}

#1


39  

Use a generic type constrained to Encodable

使用约束为Encodable的泛型类型

func saveObject<T : Encodable>(_ object: T, at location: String) {
    //Some code

    let data = try JSONEncoder().encode(object)

    //Some more code
}

#2


0  

You need to use generic function with generic type Encodable

您需要使用通用类型Encodable的泛型函数

You can't

你不能

func toData(object: Encodable) throws -> Data {
  let encoder = JSONEncoder()
  return try encoder.encode(object) // Cannot invoke 'encode' with an argument list of type '(Encodable)'
}

You can

您可以

func toData<T: Encodable>(object: T) throws -> Data {
  let encoder = JSONEncoder()
  return try encoder.encode(object)
}