/ / array con objetos json debe ser ordenado - json, swift

array con objetos json debe ser ordenado - json, swift

Los datos json se devuelven desde una llamada de red dataTask y se asignan a una matriz aquí:

   let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if let jsonarray = json as? [Any] {
self.cardArray = jsonarray
}

el json se ve así:

[
{
"deviceID":114,
"UserName":"freds@hotmail.com",
"Name":"under sink",
"UniqueId":"D0:B5:C2:F2:B8:88",
"RowCreatedDateTime":"2018-01-02T16:07:31.607"
}
]

¿Cómo puedo ordenar (descender) esta matriz en función de la propiedad json llamada RowCreatedDateTime?

Intenté esto pero no funcionó:

cardArray.sort{
$0.RowCreatedDateTime < $1.RowCreatedDateTime
}

Respuestas

2 para la respuesta № 1

Suponiendo que todos los diccionarios contienen la clave RowCreatedDateTime tienes que obtener los valores por clave. No puede usar notación de punto con un diccionario.

cardArray.sort{
($0["RowCreatedDateTime"] as! String) < $1["RowCreatedDateTime"] as! String
}

Y si sabes que el tipo de matriz es [[String:Any]] nunca lo hagas a mucho más no especificado [Any].


Declarar cardArray como una variedad de diccionarios

var cardArray = [[String:Any]]()

y analizar el JSON de esta manera

do {
if let jsonArray = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
self.cardArray = jsonArray
}
} catch { print(error) }

Considere usar Codable en Swift 4 para analizar el JSON en estructuras. Eso hace las cosas mucho más fáciles.


0 para la respuesta № 2

Hacer cardArray [[String:Any]] en lugar de [Any].

var cardArray = [[String:Any]]()

Entonces

let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if let jsonarray = json as? [[String:Any]] {
self.cardArray = jsonarray
} else {
self.cardArray = []
}

Finalmente

self.cardArray.sort {
guard let left = $0["RowCreatedDateTime"] as? String else { return true }
guard let right = $1["RowCreatedDateTime"] as? String else { return false }

return left < right
}