21

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.

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?
   }
}
swift nub
  • 2,747
  • 3
  • 17
  • 39

4 Answers4

38

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

To decode an array of Int write

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]
}

because the initializer and the CodingKeys can be inferred.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • 6
    thanks.. i was trying `[Int.self]` . Didn't realize the `.self` had to be on the outside – swift nub Jul 01 '17 at 04:47
  • 2
    I belive you can also just specify `Array.self` and `Array.self` (e.g. `[Int].self`) will be inferred from `value`’s declared type. – Joshua Nozzi Jul 02 '17 at 02:25
11

Thanks for Joshua Nozzi's hint. Here's how I implement to decode an array of Int:

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

without decoding manually.

denkeni
  • 969
  • 1
  • 10
  • 22
6

Swift 5.1

In my case, this answer was very helpful

I had a JSON in format: "[ "5243.1659 EOS" ]"

So, you can decode data without keys

struct Model: Decodable {
    let values: [Int]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        let values = try container.decode([Int].self)
        self.values = values
    }
}
let decoder = JSONDecoder()
let result = try decoder.decode(Model.self, from: data)
nomnom
  • 936
  • 10
  • 21
1

Or you can do it generic:

let decoder = JSONDecoder()
let intArray:[Int] = try? decoder.decode(T.self, from: data) 
Illya Krit
  • 925
  • 1
  • 8
  • 9