关于排序我们都知道swift有专门提供的函数sort 给我们使用,但是sort 这个函数只能对单条件进行排序,那如果我们遇到多条件和多属性的时候怎么进行排序呢?我们进行就研究下 首先我们创建一个Person 结构来进行测试验证
person 包含名、姓、和生日,我们下面会对这三个属性进行联合排序
struct Person {
let first: String
let last: String
let yearOfBirth: Int
init(first: String, last: String, yearOfBirth: Int) {
self.first = first
self.last = last
self.yearOfBirth = yearOfBirth
}
}
我们先创建一个数组:
let people = [
Person(first: "Emily", last: "Young", yearOfBirth: 2002),
Person(first: "David", last: "Gray", yearOfBirth: 1991),
Person(first: "Robert", last: "Barnes", yearOfBirth: 1985),
Person(first: "Ava", last: "Barnes", yearOfBirth: 2000),
Person(first: "Joanne", last: "Miller", yearOfBirth: 1994),
Person(first: "Ava", last: "Barnes", yearOfBirth: 1998)
]
然后我们对这个数组进行排序,规则是先按照姓排序,再按照名排序,最后是出生年份 这样我们就是三个条件联合排序了
首先我们要理清这个排序的逻辑: 多条件排序的判断方式是:先比较第一个条件的排序,只有当第一个条件相等时候,才转到下一个条件去判断,直到找到一个不相等的条件 下面我们根据这个逻辑开始谢代码:
let newPeople = people.sorted { lhs, rhs in
if lhs.first == rhs.first {
if lhs.last == rhs.last {
return lhs.yearOfBirth < rhs.yearOfBirth
}
return lhs.last < rhs.last
}
return lhs.first < rhs.first
}
print( newPeople)
这时候打印是:
[Algorithm.Person(first: "Ava", last: "Barnes", yearOfBirth: 1998),
Algorithm.Person(first: "Ava", last: "Barnes", yearOfBirth: 2000),
Algorithm.Person(first: "David", last: "Gray", yearOfBirth: 1991),
Algorithm.Person(first: "Emily", last: "Young", yearOfBirth: 2002),
Algorithm.Person(first: "Joanne", last: "Miller", yearOfBirth: 1994),
Algorithm.Person(first: "Robert", last: "Barnes", yearOfBirth: 1985)]
三个条件的排序我们知道了,但是如果是N个条件呢,这时候我们会在里面写很多if else ,这明显不符合我们的开发效率,所以我们可以改编下上面的代码,我们把N个条件进行数组话,放在一个数组里面,然后去遍历这个数组中的条件进行判断,看下行不:
typealias AreInIncreasingOrder = (Person,Person) -> Bool
let newPeople = people.sorted { lhs, rhs in
let predicates:[AreInIncreasingOrder] = [
{ $0.first < $1.first },
{ $0.last < $1.last },
{ $0.yearOfBirth < $1.yearOfBirth }
]
for predicate in predicates {
if !predicate(lhs, rhs) && !predicate(rhs,lhs) {
continue
}
return predicate(lhs,rhs)
}
return false
}
print(newPeople)
打印结果:
[Algorithm.Person(first: "Ava", last: "Barnes", yearOfBirth: 1998),
Algorithm.Person(first: "Ava", last: "Barnes", yearOfBirth: 2000),
Algorithm.Person(first: "David", last: "Gray", yearOfBirth: 1991),
Algorithm.Person(first: "Emily", last: "Young", yearOfBirth: 2002),
Algorithm.Person(first: "Joanne", last: "Miller", yearOfBirth: 1994),
Algorithm.Person(first: "Robert", last: "Barnes", yearOfBirth: 1985)]
结果跟上面的方法打印的结果一样,完美!
|