Swift - 使用多个条件对对象数组进行排序 [英] Swift - Sort array of objects with multiple criteria

查看:30
本文介绍了Swift - 使用多个条件对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组 Contact 对象:

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.

如果你的排序会用在很多地方,最好让你的类型符合Comparable 协议.这样,您可以使用 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 Contacts without ever having to duplicate the sorting code.

这篇关于Swift - 使用多个条件对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆