How to manually decode an an array in swift 4 Codable?

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)

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.


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.


Or you can do it generic:

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

Tags:

Swift

Codable