如何在Swift 4 Codable中手动解码数组?

问题描述:

这是我的代码.但是我不知道将值设置为什么.必须手动完成此操作,因为实际结构比此示例稍微复杂些.

Here is my code. But I do not know what to set the value to. It has to be done manually because the real structure is slightly more complex than this example.

请帮忙吗?

struct Something: Decodable {
   value: [Int]

   enum CodingKeys: String, CodingKeys {
      case value
   }

   init (from decoder :Decoder) {
      let container = try decoder.container(keyedBy: CodingKeys.self)
      value = ??? // < --- what do i put here?
   }
}

由于一些错误/错别字,您的代码无法编译.

Your code doesn't compile due to a few mistakes / typos.

要解码 Int 个数组,请写入

struct Something: Decodable {
    var value: [Int]

    enum CodingKeys: String, CodingKey {
        case value
    }

    init (from decoder :Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        value = try container.decode([Int].self, forKey: .value)
    }
}


但是,如果问题中的示例代码代表整个结构,则可以简化为


But if the sample code in the question represents the entire struct it can be reduced to

struct Something: Decodable {
    let value: [Int]
}

因为可以推断出初始化程序和 CodingKeys .

because the initializer and the CodingKeys can be inferred.