{
\"values\":[
[1,1,7,\"Azuan Child\",\"Anak Azuan\",\"12345\",\"ACTIVE\",\"Morning\",7,12,\"2017-11-09 19:45:00\"],
[28,1,0,\"Azuan Child2\",\"Amran\",\"123456\",\"
Solution
public struct UncertainValue: Decodable {
public var tValue: T?
public var uValue: U?
public var value: Any? {
return tValue ?? uValue
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
tValue = try? container.decode(T.self)
uValue = try? container.decode(U.self)
if tValue == nil && uValue == nil {
//Type mismatch
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context(codingPath: [], debugDescription: "The value is not of type \(T.self) and not even \(U.self)"))
}
}
}
Example
{
"results": [{
"name": "Gala",
"age": 1,
"type": "Pug"
}, {
"name": "Keira",
"age": "7",
"type": "Collie Rough"
}]
}
Usage
struct Dog: Decodable, CustomStringConvertible {
var name: String
var age: UncertainValue
var type: String
var description: String {
return "\(name) is a lovely \(type) of \(age.value!) years old"
}
}