Mc.Lover
Mc.Lover

Reputation: 4994

Swift: getting error while decoding using CodingKey

I have created a model and I need to try to add value to one of the CodingKey's case

struct Model {
  let name: String
  let location: String
  let descriptions: String

}
    
enum CodingKeys: String, CodingKey {

  case name = "NAME"
  case location = "LOCATION"
  case descriptions = "INFO-\(NSLocalizedString("Language", comment: ""))"
    
}
    
init(from decoder: Decoder) throws {

  let container = try decoder.container(keyedBy: CodingKeys.self)
  .
  .
  descriptions = try container.decode(String.self, forKey: .descriptions)
        
}

Now compiler gives me this error

🛑 Raw value for enum case must be a literal

How can I fix this error?

Upvotes: 0

Views: 320

Answers (1)

Sweeper
Sweeper

Reputation: 271410

You don't have to use an enum for CodingKeys. You can also use a struct with static lets. It's just a bit more boilerplate:

struct Model: Decodable {
    let name: String
    let location: String
    let descriptions: String

        
    struct CodingKeys: CodingKey {
        let intValue: Int? = nil
        let stringValue: String
        
        init(stringValue: String) {
            self.stringValue = stringValue
        }
        
        init?(intValue: Int) {
            return nil
        }
        
        static let name = CodingKeys(stringValue: "name")
        static let location = CodingKeys(stringValue: "location")
        static let description = CodingKeys(stringValue: "INFO-\(NSLocalizedString("Language", comment: ""))")
    }
        
    init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        location = try container.decode(String.self, forKey: .location)
        descriptions = try container.decode(String.self, forKey: .description)
            
    }
}

Upvotes: 1

Related Questions