Comparable 有两个先决条件: 类型要满足Equatable protocol和使用<操作符。
struct Employee: Equatable,Comparable {
var firstname: String
var lastname: String
var title: String
//相同实例的先决条件
static func == (lhs: Employee, rhs: Employee) -> Bool {
return lhs.firstname == rhs.firstname && lhs.lastname == rhs.lastname
&& lhs.title == rhs.title
}
//排序依据
static func < (lhs:Employee, rhs:Employee) -> Bool {
return lhs.lastname < rhs.lastname
}
}
let employee1 = Employee(firstname: "Si", lastname: "li", title: "PL")
let employee2 = Employee(firstname: "Paul", lastname: "maivd", title: "TL")
let employee3 = Employee(firstname: "Lulu", lastname: "ain", title: "Sales")
let employeeall = [employee1,employee2,employee3]
//此处使用闭包的函数 - sorted(by:)
let employeesorted = employeeall.sorted(by: <)
for employee in employeesorted {
print(employee)
}
Employee(firstname: "Lulu", lastname: "ain", title: "Sales")
Employee(firstname: "Si", lastname: "li", title: "PL")
Employee(firstname: "Paul", lastname: "maivd", title: "TL")
添加Int,可以自由排序(升序或者降序)
struct Employee: Equatable,Comparable {
var firstname: String
var lastname: String
var title: String
var age: Int
static func == (lhs: Employee, rhs: Employee) -> Bool {
return lhs.firstname == rhs.firstname && lhs.lastname == rhs.lastname
&& lhs.title == rhs.title
}
static func < (lhs:Employee, rhs:Employee) -> Bool {
return lhs.age < rhs.age
}
}
let employee1 = Employee(firstname: "Si", lastname: "li", title: "PL", age: 50)
let employee2 = Employee(firstname: "Paul", lastname: "maivd", title: "TL", age: 40)
let employee3 = Employee(firstname: "Lulu", lastname: "ain", title: "Sales", age: 60)
let employeeall = [employee1,employee2,employee3]
//此处使用的闭包的函数
let employeesorted = employeeall.sorted(by: <)
for employee in employeesorted {
print(employee)
}
输出结果:
Employee(firstname: "Paul", lastname: "maivd", title: "TL", age: 40)
Employee(firstname: "Si", lastname: "li", title: "PL", age: 50)
Employee(firstname: "Lulu", lastname: "ain", title: "Sales", age: 60)
如果将 sorted(by: <) 改为'>'
输出结果将随之发生变化:
Employee(firstname: "Lulu", lastname: "ain", title: "Sales", age: 60)
Employee(firstname: "Si", lastname: "li", title: "PL", age: 50)
Employee(firstname: "Paul", lastname: "maivd", title: "TL", age: 40)