使用JSONEncoder以Codable作为类型对变量进行编码

Den*_*lko 35 serialization protocols ios swift codable

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

例如:

struct Test: Codable {
    var someString: String?
}

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

let result = try JSONEncoder().encode(testItem)
Run Code Online (Sandbox Code Playgroud)

这很好,没有问题.

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

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

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

    // Some more code
}
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

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

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

open func encode<Value>(_ value: Value) throws -> Data where Value : Encodable
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 64

使用约束的泛型类型 Encodable

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

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

    //Some more code
}
Run Code Online (Sandbox Code Playgroud)

  • 什么的?有人可以解释我这种行为吗?它对我没有任何意义 (8认同)
  • Codable需要能够确定其对象类型.使用`Any`作为类型会混淆它,因为它不知道哪个类型的`init(来自解码器:)`初始化程序要调用.该函数本质上以通用的形式提供缺少的信息.代码可以通过类型推断来计算要使用的类型. (2认同)