If in your JSON the value associated with the key can be sometimes Float
and sometimes String
(in addition to fixing this error in the 😉 backend), you can follow this approach.
Let's say this is your "funny" JSON
let data = """
[
{
"magicField": "one"
},
{
"magicField":1
}
]
""".data(using: .utf8)!
Well, how can we elegantly present this type of data in Swift?
struct Element:Decodable {
let magicField: ???
}
, magicField
, Float
String
.
... Enum 😅
enum QuantumValue: Decodable {
case float(Float), string(String)
init(from decoder: Decoder) throws {
if let float = try? decoder.singleValueContainer().decode(Float.self) {
self = .float(float)
return
}
if let string = try? decoder.singleValueContainer().decode(String.self) {
self = .string(string)
return
}
throw QuantumError.missingValue
}
enum QuantumError:Error {
case missingValue
}
}
, QuantumValue
Float
String
. 1 1 .
JSON
struct Element:Decodable {
let magicField: QuantumValue
}
. JSON.
if let elms = try? JSONDecoder().decode([Element].self, from: data) {
print(elms)
}
[
Element(magicField: QuantumValue.string("one")),
Element(magicField: QuantumValue.float(1.0))
]
( )
switch magicField {
case .string(let text):
println(text)
case .float(let num):
println(num)
}