0

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?

1
  • 1
    As the error says, you must use a literal, not a computed value. You will either need to use a custom decoder or decode to a dictionary of [String:String] and select the required value Commented May 29, 2022 at 8:36

1 Answer 1

1

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)
            
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.