0

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.

Jason Fel
  • 921
  • 4
  • 10
  • 29

1 Answers1

2

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.
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129
  • That is awesome thank you. I will accept the answer when I can in 7 minutes. – Jason Fel Sep 09 '16 at 22:08
  • Keep in mind that if `number` is a `String` then this will do an alphabetic sort, not a numeric sort. In other words, bus 200 will come before bus 8, for example. – rmaddy Sep 09 '16 at 22:09
  • Should I use sortInPlace instead of sort? Xcode is giving me a warning. – Jason Fel Sep 09 '16 at 22:10
  • Sort using closure, but take care of the swift version. Swift 2.3 -> `sort` returns a sorted array, but `sortInPlace` sorts the same array Swift 3.0 -> `sorted` returns a sorted array, but `sort` sorts the same array – vj9 Sep 09 '16 at 22:12