Trying to return a JSON output using Swift's Codable library. I've set up a struct to capture a 'default' value from my JSON. The 'default' value currently has two datatype outputs, string or int. I'm trying to return the string value if the 'default' is string and the int value if it's is an int.
struct Settings: Codable {
let configDefault: IntOrString
let name: String?
}
enum IntOrString: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let int = try? container.decode(Int.self) {
self = .integer(int)
return
}
if let string = try? container.decode(String.self) {
self = .string(string)
return
}
throw DecodingError.typeMismatch(IntOrString.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Default"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
All this gets decoded into a value defaultValueHolder
let defaultValueHolder = try JSONDecoder().decode(Settings.self, from: jsonString)
Using Eureka's form library i'm trying to set the table value as the default String or Int returned from the JSON.
form +++ Section ("Values")
// dynamically generates rows
for values in defaultValueHolder {
form.last! <<< IntRow() {
$0.tag = values.name
$0.title = values.name
$0.value = values.IntOrString
}
The issue is when trying to add a value to $0.value I cannot cast it as a IntORString enum type and have to return either the int or string depending if a IntRow or TextRow is declared.