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.

0

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

4 Comments

That is awesome thank you. I will accept the answer when I can in 7 minutes.
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.
Should I use sortInPlace instead of sort? Xcode is giving me a warning.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.