在Swift中可以通過實現(xiàn)Equatable協(xié)議使自定義類型支持==以及!=這兩種運算符;Comparable協(xié)議繼承于Equatable,實現(xiàn)Comparable協(xié)議可以在Equatable的基礎上使類型支持>,>=,<,<=四種運算符。
import Foundation
struct Point:Comparable{
let x:Int
let y:Int
//實現(xiàn)Equatable
static func ==(p1:Point,p2:Point) ->Bool{
return (p1.x==p2.x) && (p1.y==p2.y)
}
//實現(xiàn)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