Using Swift 4's Encoder
& Decoder
protocol and JSONDecoder
how do I initialize a struct of type Codeable
using a key from a given JSON.
i.e. Given the JSON below I wish to only use results
to initialize Example
{
"boolean": true,
"number": 123,
"results": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
struct Example: MDB, Codeable{
var a: String
var b: String
var c: String
}
public static func initalize<T: Codable & MDBItem>(json: Data) -> [T]{
var items = [T]()
let decoder = JSONDecoder()
do {
//How do I initialize `T` using a key from the JSON given
//ie. decoder.decode([T].self, from: json["results"])
// Or decoder.decode(["results", [T].self, from: json)
items = try decoder.decode([T].self, from: json)
} catch {
print("error trying to convert data to JSON")
}
return items
}