Swift: 使用 CodingKey 解码时出错

Swift: getting error while decoding using CodingKey

我创建了一个模型,我需要尝试为 CodingKey 的案例之一增加价值

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

现在编译器给我这个错误

Raw value for enum case must be a literal

我该如何解决这个错误?

没有CodingKey使用枚举。您还可以使用带有 static let 的结构。只是有点样板:

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