sbkl sbkl - 4 months ago 61
Swift Question

Swift - Sort array of objects with multiple criteria

I have an array of Contact object:

var contacts:[Contact] = [Contact]()

Contact class:

Class Contact:NSOBject {
var firstName:String!
var lastName:String!

And I would like to sort that array by lastName and then by firstName in case some contacts got the same lastName.

Today, I'm able to sort by one of those criteria. But not both.

contacts.sortInPlace({$0.lastName < $1.lastName})

How could I add more criteria to sort this array?

Thank you.


Think of what "sorting by multiple criteria" means. It means that two objects are first compared by one criteria. Then, if those criteria are the same, ties will be broken by the next criteria, and so on until you get the desired ordering.

    if $0.lastName != $1.lastName {
        return $0.lastName < $1.lastName
    else {
        //last names are the same, break ties by first name
        return $0.firstName < $1.firstName

What you're using here is the sortInPlace(_:) method, which depends on the given closure to determine the sorting. If your sorting will be used in many places, it may be better to instead use sortInPlace() method, which only works on MutableCollectionType instances which also conform to the Comparable protocol. This way, you can sort a collection of Contacts without ever having to duplicate the sorting code.