You can use a small trick to get around the unknown key issue: create a helper struct for your Strain
struct, make that helper struct Codable
, decode the response as [String:Helper]
, then create a custom initializer that takes 2 input arguments, the name of the strain and a Helper
instance.
This way you can store the name
as a property of Strain
and you won't need an overcomplicated decoding to circumvent the issue of the unknown top level Dictionary
key.
struct Strain {
var name: String
var id: Int
var race: String
var flavors: [String]
var effects: [String: [String]]
init(from helper: StrainHelper, with name:String){
self.name = name
self.id = helper.id
self.race = helper.race
self.flavors = helper.flavors
self.effects = helper.effects
}
}
struct StrainHelper: Codable {
var id: Int
var race: String
var flavors: [String]
var effects: [String: [String]]
}
do {
let strainHelper = try JSONDecoder().decode([String:StrainHelper].self, from: data)
guard let strainName = strainHelper.keys.first else {throw NSError(domain: "No key in dictionary",code: 404)}
let strain = Strain(from: strainHelper[strainName]!, with: strainName)
} catch {
print(error)
}