-1

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"))
Mickael Belhassen
  • 2,970
  • 1
  • 25
  • 46
  • This enum doesn't have a raw value, It has associated values. – vadian Feb 26 '19 at 08:36
  • Check the example code in https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html: *"You can check the different barcode types using a switch statement ... This time, however, the associated values are extracted as part of the switch statement."* – Martin R Feb 26 '19 at 08:38
  • Thanks its work Martin – Mickael Belhassen Feb 26 '19 at 08:47

1 Answers1

4

One solution is to add two computed properties in the enum to get the associated values.

var stringValue : String? {
    guard case let .string(value) = self else { return nil }
    return value
}

var intValue : Int? {
    guard case let .integer(value) = self else { return nil }
    return value
}

And use it

answer.id?.intValue
vadian
  • 274,689
  • 30
  • 353
  • 361