Swift - Sort array of objects with multiple criteria

后端 未结 8 1124
北荒
北荒 2020-11-22 11:19

I have an array of Contact objects:

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

Contact class:

Class Contact:NSOBjec         


        
8条回答
  •  青春惊慌失措
    2020-11-22 12:10

    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.

    let sortedContacts = contacts.sort {
        if $0.lastName != $1.lastName { // first, compare by last names
            return $0.lastName < $1.lastName
        }
        /*  last names are the same, break ties by foo
        else if $0.foo != $1.foo {
            return $0.foo < $1.foo
        }
        ... repeat for all other fields in the sorting
        */
        else { // All other fields are tied, break ties by last name
            return $0.firstName < $1.firstName
        }
    }
    

    What you're seeing here is the Sequence.sorted(by:) method, which consults the provided closure to determine how elements compare.

    If your sorting will be used in many places, it may be better to make your type conform to the Comparable protocol. That way, you can use Sequence.sorted() method, which consults your implementation of the Comparable.<(_:_:) operator to determine how elements compare. This way, you can sort any Sequence of Contacts without ever having to duplicate the sorting code.

提交回复
热议问题