Search code examples
swiftcodable

How to manually decode an Array using Swift Codable?


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

Solution

  • 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.