정의
이 프로토콜을 준수하는 타입은 <, <=, >, >= 연산자로 비교할 수 있습니다.
public protocol Comparable : Equatable {
static func < (lhs: Self, rhs: Self) -> Bool
static func <= (lhs: Self, rhs: Self) -> Bool
static func >= (lhs: Self, rhs: Self) -> Bool
static func > (lhs: Self, rhs: Self) -> Bool
}
조건
사용
let currentTemp = 73
if currentTemp >= 90 {
print("It's a scorcher!")
} else if currentTemp < 65 {
print("Might need a sweater today.")
} else {
print("Seems like picnic weather!")
}
// Prints "Seems like picnic weather!"
var measurements = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]
measurements.sort()
print(measurements)
// Prints "[1.1, 1.2, 1.2, 1.3, 1.5, 1.5, 2.9]"
예제
extension Date: Comparable {
static func < (lhs: Date, rhs: Date) -> Bool {
if lhs.year != rhs.year {
return lhs.year < rhs.year
} else if lhs.month != rhs.month {
return lhs.month < rhs.month
} else {
return lhs.day < rhs.day
}
}
}
예외
outside the domain of meaningful arguments for the purposes of the
Comparable
protocol Docs
FloatingPoint.nan의 경우 비교가 안 된다.
let a: [Double] = [3, 1, 2, .nan, 3, 10, 1]
print(a.sorted())
[1.0, 2.0, 3.0, nan, 1.0, 3.0, 10.0]