Swift学习笔记

Swift - Comparable

2022-03-26  本文已影响0人  aven_kang
class Student : Comparable {
    
    static func < (lhs: Student, rhs: Student) -> Bool {
        lhs.score < rhs.score
    }
    
    static func > (lhs: Student, rhs: Student) -> Bool {
        lhs.score > rhs.score
    }
    
    static func == (lhs: Student, rhs: Student) -> Bool {
        lhs.score == rhs.score
    }
    
    static func <= (lhs: Student, rhs: Student) -> Bool {
        !(lhs > rhs)
    }
    
    static func >= (lhs: Student, rhs: Student) -> Bool {
        !(lhs < rhs)
    }
    
    
    var score: Int
    var age:Int
    init(age:Int,score:Int) {
        self.age = age
        self.score = score
    }
    
}
比较两个实例的大小
1.遵守Comparable
2.重载相应的运算符
上一篇 下一篇

猜你喜欢

热点阅读