I'm trying to decode a specific class based on the contents of the encoded data.
class Vehicle: Codable {
enum Kind: Int, Codable {
case car = 0, motorcycle = 1
}
let brand: String
let numberOfWheels: Int
}
class Car: Vehicle {}
class MotorCycle: Vehicle {}
As you can see, I have a generic Vehicle type used to encode and decode vehicles. This works fine for basic decoding shown below.
let car = "{\"kind\": 0, \"brand\": \"Ford\", \"number_of_wheels\": 4}".data(using: .utf8)!
let motorCycle = "{\"kind\": 1, \"brand\": \"Yamaha\", \"number_of_wheels\": 2}".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
// Outputs a Project.Car
let ford = try! decoder.decode(Car.self, from: car)
// Outputs a Project.MotorCycle
let yamaha = try! decoder.decode(MotorCycle.self, from: motorCycle)
But what if I want to decode an array of vehicles, but have them decoded as a specific type?
let combined = "[{\"kind\": 0, \"brand\": \"Ford\", \"number_of_wheels\": 4}, {\"kind\": 1, \"brand\": \"Yamaha\", \"number_of_wheels\": 2}]".data(using: .utf8)!
// Outputs [Project.Vehicle, Project.Vehicle]
print(try! decoder.decode([Vehicle].self, from: combined))
How can I have the decoder output an array of vehicles, but typed vehicles, by using the kind property in the JSON data. As per example [Project.Car, Project.MotorCycle] if possible at all.