Swift-使用多个条件对对象数组进行排序 [英] Swift - Sort array of objects with multiple criteria
问题描述
我有一个Contact
个对象的数组:
I have an array of Contact
objects:
var contacts:[Contact] = [Contact]()
联系方式:
Class Contact:NSOBject {
var firstName:String!
var lastName:String!
}
我想先按lastName
然后按firstName
对该数组进行排序,以防某些联系人使用相同的lastName
.
And I would like to sort that array by lastName
and then by firstName
in case some contacts got the same lastName
.
我能够按其中一个条件进行排序,但不能同时按两个条件进行排序.
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?
推荐答案
思考按多个条件排序"的含义.这意味着首先通过一个条件比较两个对象.然后,如果这些条件相同,则领带将被下一个条件破坏,依此类推,直到获得所需的排序.
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
}
}
您在这里看到的是 Sequence.sorted(by:)
方法 ,它会参考提供的闭包来确定元素的比较方式.
What you're seeing here is the Sequence.sorted(by:)
method, which consults the provided closure to determine how elements compare.
如果您的排序将在许多地方使用,最好使您的类型符合 Sequence.sorted()
方法,该方法会咨询您的实现 Comparable.<(_:_:)
运算符的操作,以确定元素之间的比较方式.这样,您可以对Contact
中的任何Sequence
进行排序,而不必重复排序代码.
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 Contact
s without ever having to duplicate the sorting code.
这篇关于Swift-使用多个条件对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!