Swift - Sort array of objects with multiple criteria

后端 未结 8 1054
北荒
北荒 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:03

    Another simple approach for sorting with 2 criteria is shown below.

    Check for the first field, in this case it is lastName, if they are not equal sort by lastName, if lastName's are equal, then sort by the second field, in this case firstName.

    contacts.sort { $0.lastName == $1.lastName ? $0.firstName < $1.firstName : $0.lastName < $1.lastName  }
    

提交回复
热议问题