Why does code print with surrounding parenthesis and with the prefix int or string? For example:
code: string("Gate: 2312231")
How can I just have it print code: 2312231
and nothing more? Try the following code in Playgrounds to see the the printed values. I appreciate the help, let me know if there are any questions.
let data = """
[
{
"date": "2022-05-04",
"code": 122312,
"notes": "Take keys"
},
{
"date": "2022-05-04",
"code": "Gate: 2312231",
"notes": "Take Box"
}
]
""".data(using: .utf8)!
enum Code: Decodable {
case int(Int)
case string(String)
}
struct Item: Decodable {
var date: Date
var code: Code
var notes: String
enum CodingKeys: String, CodingKey {
case date, code, notes
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.date = try container.decode(Date.self, forKey: .date)
self.notes = try container.decode(String.self, forKey: .notes)
if let value = try? container.decode(Int.self, forKey: .code) {
self.code = .int(value)
} else if let value = try? container.decode(String.self, forKey: .code) {
self.code = .string(value)
} else {
let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Unable to decode value for `code`")
throw DecodingError.typeMismatch(Code.self, context)
}
}
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let items = try! decoder.decode([Item].self, from: data)
for item in items {
print("date: \(item.date.description)")
print("code: \(item.code)")
print("notes: \(item.notes)")
print()
}