Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
Problema al decodificar JSON | Rápido

Tengo un problema al completar dinámicamente la date asociada con cada sección. El valor de agrupado se deriva actualmente de agrupar los datos JSON sin procesar por ID de ruta

Puede ver que actualmente estoy usando un valor estático para la fecha como prueba, mientras que $0.key representa el valor de myID dinámicamente.

¿Cómo se puede agregar también el valor dinámico de myDate en lugar de "prueba"?

Variables:

 var sections = [mySections]() var structure = [myStructure]()

Actualmente esto es cierto

sections.map(\.id) == [8,4]

Al final, esto también debe ser cierto.

sections.map(\.date) == [2021-01-20, 2021-01-18]

Descodificación:

 do { let decoder = JSONDecoder() let res = try decoder.decode([myStructure].self, from: data) let grouped = Dictionary(grouping: res, by: { $0.myID }) _ = grouped.keys.sorted() sections = grouped.map { mySections(date: "test", id: $0.key, items: $0.value) } .sorted { $0.id > $1.id } }

Estructura:

 struct mySections { let date : String let id : Int var items : [myStructure] } struct myStructure: Decodable { let name: String let type: String let myID: Int let myDate: String }

JSON de ejemplo:

 [ { "name": "Jeff", "type": "large", "myID": 8, "myDate": "2021-01-20" }, { "name": "Jessica", "type": "small", "myID": 4, "myDate": "2021-01-18" }, { "name": "Beth", "type": "medium", "myID": 4, "myDate": "2021-01-18" } ]
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Entonces, ¿quieres que se agrupe por número de identificación y cadena de fecha? Crearía una estructura Hashable para esos dos valores.

 struct Section { let date: String let id: Int var items: [Item] } extension Section { struct Header: Hashable { let date: String let id: Int } } struct Item: Decodable { let name: String let type: String let myID: Int let myDate: String }

Y

 let decoder = JSONDecoder() let res = try decoder.decode([Item].self, from: data) let sections = Dictionary(grouping: res) { Section.Header(date: $0.myDate, id: $0.myID) } .sorted { $0.key.id > $1.key.id } .map { Section(date: $0.key.date, id: $0.key.id, items: $0.value) }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!