I have a class with a field type ID (enum class), both are codable, I can not read the raw value of the enum, what should I implement other
My code:
struct Answer: Codable {
let id: ID?
let message: String?
enum CodingKeys: String, CodingKey {
case id = "Id"
case message = "Message"
}
}
enum ID: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(ID.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for ID"))
}
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)
}
}
}
How to read the value like this answer.id?.rawValue
In the sound I get the id can be an integer or string, so automatically with the class codable swift know instance the good enum.
So if I receive an int I want:
answer.id?.rawValue
//output 4
So if I receive an string I want:
answer.id?.rawValue
//output "male"
When I print this I notice that it is associated with a value:
print(answer.id.debugDescription)
//Output: Optional(fitto.ID.integer(2)) or if is string Optional(fitto.ID.string("female"))