在Swift中可以通过实现Equatable协议使自定义类型支持==以及!=这两种运算符;Comparable协议继承于Equatable,实现Comparable协议可以在Equatable的基础上使类型支持>,>=,<,<=四种运算符。
import Foundation
struct Point:Comparable{
let x:Int
let y:Int
//实现Equatable
static func ==(p1:Point,p2:Point) ->Bool{
return (p1.x==p2.x) && (p1.y==p2.y)
}
//实现Comparable
static func <(p1:Point,p2:Point) ->Bool{
return (p1.x<p2.x) && (p1.y<p2.y)
}
}
let p1=Point(x: 3, y: 4)
let p2=Point(x: 3, y: 4)
let p3=Point(x: 3, y: 5)
let p4=Point(x: 2, y: 2)
print(p1 == p2)//true
print(p1 == p3)//false
print(p1 <= p3)//true
print(p1 <= p4)//false