Jason Fel Jason Fel - 2 months ago 8
iOS Question

How can I sort an array of Bus objects by their bus number (buses.number)?

Lets say I have the following array of Bus objects:

var buses = [Bus]()


After the buses array fills up I would like to sort the array of buses by bus number (which is a String for example "501"). Each Bus object has a bus number (buses[index].number). There are no duplicate bus numbers. How can I I do this sort? I see filter around but i'm not really sure how to apply it.

Answer

It's so simple by sort method in swift,

let sortedBuses = buses.sort({ $0.number > $1.number })

or

buses.sortInPlace({ $0.number > $1.number }) // this sorts arrays and saves it in self.