How to manually decode an array in swift 4 codable?

Here is my code. But I do not know how to set the value. This needs to be done manually, because the real structure is a little more complicated than this example.

Any help please?

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?
   }
}
+4
source share
2 answers

Your code does not compile due to several errors / typos.

To decode an array Intwrite

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 whole structure, it can be reduced to

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

since the initializer and CodingKeyscan be deduced.

+11
source

Thanks for the tip Joshua Nozzi. This is how I implement to decode an Int array:

let decoder = JSONDecoder()
let intArray = try? decoder.decode([Int].self, from: data)

without manual decoding.

0
source

Source: https://habr.com/ru/post/1680537/


All Articles