如何在Swift 4 Codable中手动解码数组? [英] How to manually decode an an array in swift 4 Codable?

查看:61
本文介绍了如何在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.

这篇关于如何在Swift 4 Codable中手动解码数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆