Sort array of objects in swift

1

I need to sort a array alphabetically in swift .

I found this code:

var images : [imageFile] = []
images.sort({ $0.fileID > $1.fileID })

But I do not know how I can apply it to my array

My code:

if let dataFromString = datosJson.data(using: String.Encoding.utf8, allowLossyConversion: false) {
    let json = JSON(data: dataFromString)
    for (index, subJson):(String, JSON) in json {
        for a in 0 ..< subJson.count {
            self.currentlyConstructingObjeto = Objeto()
            self.currentlyConstructingObjeto.nombre = subJson[a]["nombre"].stringValue
            self.currentlyConstructingObjeto.tipo = subJson[a]["tipo"].stringValue
            self.currentlyConstructingObjeto.id = subJson[a]["id"].stringValue
            self.objetos.append(self.currentlyConstructingObjeto)
        }
    }
}

The array that I have to sort is self.objetos

    
asked by 18.10.2016 в 10:10
source

2 answers

1

You could try this after having already filled in the data of the array, what it does is to order the field name from least to greatest.

objetos.sorted { $0.nombre < $1.nombre }
    
answered by 18.10.2016 / 10:46
source
1

For array of objects:

items = items.sorted(by: { (item1, item2) -> Bool in
    return item1.product.name.compare(item2.product.name) == ComparisonResult.orderedAscending
})
    
answered by 20.04.2018 в 16:45