Sorting Information with Comparable -Swift中实例的排序问题

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)
}


 输出:将lastname 排序后输出结果如下


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)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值