24

I do not know what to set the value to in the code below. 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?
   }
}

4 Answers 4

42

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks.. i was trying [Int.self] . Didn't realize the .self had to be on the outside
I belive you can also just specify Array.self and Array<Int>.self (e.g. [Int].self) will be inferred from value’s declared type.
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.

Comments

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)

Comments

1

Or you can do it generic:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.