Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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.

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?
   }
}
like image 562
swift nub Avatar asked Jul 01 '17 04:07

swift nub


People also ask

What is codable in Swift 4?

Codable. Introduced in Swift 4, the Codable API enables us to leverage the compiler in order to generate much of the code needed to encode and decode data to/from a serialized format, like JSON. Codable is actually a type alias that combines two protocols — Encodable and Decodable — into one.

What data formats are supported by Swift's codable protocols?

Swift’s Codable protocols, paired with keyed and unkeyed decoding containers, allow for sophisticated decoding of data. The most common data format to which these apply is JSON, but the Codable protocols work with any data format that has a hierarchical structure. One such example is the property list format.

How to decode JSON data in Swift?

The three-step process to decode JSON data in Swift. In any app, you have to go through three steps to decode the JSON data you get from a REST API. Perform a network request to fetch the data. Feed the data you receive to a JSONDecoder instance. Map the JSON data to your model types by making them conform to the Decodable protocol.

What does encodable and decodable mean in Swift?

Encodable means an object is convertible from Swift to JSON (or to another external representation). Decodable means an object is convertible from JSON (or other external representation) to Swift. Practically every iOS app handles JSON data in one way or another.


2 Answers

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.

like image 160
vadian Avatar answered Oct 12 '22 19:10

vadian


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.

like image 45
denkeni Avatar answered Oct 12 '22 19:10

denkeni