Codable/Decodable should decode Array with Strings

Viewed 3971

Why is the names Array not decoding?

Prepared for Playground, Simple paste this into your playground

import Foundation

struct Country : Decodable {

    enum CodingKeys : String, CodingKey {
        case names
    }

    var names : [String]?
}

extension Country {
    public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        names = try values.decode([String]?.self, forKey: .names)!
    }
}

let json = """
 [{
    "names":
      [
       "Andorre",
       "Andorra",
       "アンドラ"
      ]
 },{
    "names":
      [
       "United Arab Emirates",
       "Vereinigte Arabische Emirate",
       "Émirats Arabes Unis",
       "Emiratos Árabes Unidos",
       "アラブ首長国連邦",
       "Verenigde Arabische Emiraten"
      ]
  }]
""".data(using: .utf8)!

let decoder = JSONDecoder()
do {
    let countries = try decoder.decode([Country].self, from: json)
    countries.forEach { print($0) }
} catch {
    print("error")
}
1 Answers
Related