Is it possible with the Decodable
protocol in Swift 4 to decode a JSON object when the type to decode to is only known at runtime?
I have a registry of sorts which maps a String
identifier to the type we want to decode to, as below:
import Foundation
struct Person: Decodable {
let forename: String
let surname: String
}
struct Company: Decodable {
let officeCount: Int
let people: [Person]
}
let registry: [String:Decodable.Type] = [
"Person": Person.self,
"Company": Company.self
]
let exampleJSON = """
{
"forename": "Bob",
"surname": "Jones"
}
""".data(using: .utf8)!
let t = registry["Person"]!
try! JSONDecoder().decode(t, from: exampleJSON) // doesn't work :-(
Am I on the right lines here or is there a better way?