Thursday, January 23, 2020

Swift enum - make Encodable

Suppose you have struct like below to encode as { status: "",  macName: "" }

struct Request: Encodable {

      var status: MacStatus
      var macName: String
}

enum MacStatus {

    case running
    case notRunning
}

Now we want to make the enum  MacStatus as encodable. So we can use singleValueContainer

extension MacStatus: Encodable {

    var josnKey: String {
        switch self {
        case . running:
            return "Running"
        case . notRunning:
            return "Not Running"
   }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(josnKey)
    }
}

Another way is below:

enum MacStatus: String, Encodable {

    case running
    case notRunning

   var rawValue {
       switch self {
           case . running:
                return "Running"
           case . notRunning:
                return "Not Running"
       }
   }
}