Search code examples
iosswiftcodingkey

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?


Solution

  • 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)
                
        }
    }