I have a JSON which has a variable of two different types (same as here).
I used the code which is marked as solution in the linked question and I want to print a variable in a for loop:
struct GetEvents: Decodable{
var id: String?
var expansion: String?
var distance: Distance?
}
enum Distance: Codable {
case int(Int)
case string(String)
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .int(let v): try container.encode(v)
case .string(let v): try container.encode(v)
}
}
init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer()
do {
self = .int(try value.decode(Int.self))
} catch DecodingError.typeMismatch {
self = .string(try value.decode(String.self))
}
}
enum ParseError: Error {
case notRecognizedType(Any)
}
}
I try to print all variables with a for-loop because i have multiple objects inside the object.
for i in 0...(getEventsText.items.count - 1) {
if let idAsString = getEventsText.items[i].id {
print(idAsString)
}
if let distanceAsString = getEventsText.items[i].distance {
print(distanceAsString)
}
if let epansionAsString = getEventsText.items[i].offer_expansion {
print(expansionAsString)
}
I get the id and the expansion but the distance is showing as int(-1) and not as -1
If I just output it like this:
for x in range getEventsText.items {
print(x)
}
It prints:
GetEvents(id: Optional("7576"), distance: Swift.ImplicitlyUnwrappedOptional<DB_Read_enums_Test1.Distance>.some(DB_Read_enums_Test1.Distance.int(0)), expansion: Optional("0"))