Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
Cómo ignorar los valores nil json en codificable

Actualmente estoy recibiendo recibos tanto Auto-Renewable como Non-Renewable . Pero el Non-Renewable no regresa con la clave expires_date json. ¿Cómo puedo ignorar esto? Estoy tratando de evitar que expires_date opcional. Cuando lo hago opcional, Apple envía una respuesta. ¿Hay alguna forma en que pueda decodificar el json sin hacer que expires_date opcional?

 struct Receipt: Codable { let expiresDate: String private enum CodingKeys: String, CodingKey { case expiresDate = "expires_date" } }

Ahora mismo puedo obtener

"No hay valor asociado con la clave CodingKeys(stringValue: \"expires_date\", intValue: nil) (\"expires_date\")".

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Tendrá que implementar su propio init(from: Decoder) y usar decodeIfPresent(_:forKey:) antes de que nil se fusione con un valor predeterminado.

 struct Receipt: Codable { let expiresDate: String enum CodingKeys: String, CodingKey { case expiresDate = "expires_date" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.expiresDate = try values.decodeIfPresent(String.self, forKey: .expiresDate) ?? "1970" //Default value } }

NOTA:

  • Si Receipt tiene más pares clave-valor, también tendrá que decodificarlos manualmente.

Ejemplo de uso:

 let data = """ [{ "expires_date": "2019" }, { }] """.data(using: .utf8)! do { let obj = try JSONDecoder().decode([Receipt].self, from: data) print(obj) } catch { print(error) }
over 4 years ago · Santiago Trujillo Denunciar

0

¿Qué tal decodificarlo manualmente?

 struct Receipt: Codable { let expiresDate: String private enum CodingKeys: String, CodingKey { case expiresDate = "expires_date" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) if let expDate = try? values.decode(String.self, forKey: .expiresDate) { self.expiresDate = expDate } else { self.expiresDate = "sth" } } }

Ejemplo:

 struct Receipt: Codable { let expiresDate: String let b: String private enum CodingKeys: String, CodingKey { case expiresDate = "expires_date" case b = "b" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) if let expDate = try? values.decode(String.self, forKey: .expiresDate) { self.expiresDate = expDate } else { self.expiresDate = "sth" } b = try values.decode(String.self, forKey: .b) } } let a = """ { "b": "asdf" } """.data(using: .utf8)! let myStruct = try JSONDecoder().decode(Receipt.self, from: a) print(myStruct) //Receipt(expiresDate: "sth", b: "asdf")
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda