Skip to content

Instantly share code, notes, and snippets.

@rl-pavel
Last active October 20, 2020 03:50
Show Gist options
  • Save rl-pavel/276adc678c1ddabac3f179212f1e95c1 to your computer and use it in GitHub Desktop.
Save rl-pavel/276adc678c1ddabac3f179212f1e95c1 to your computer and use it in GitHub Desktop.
Optional Comparable and Equatable helpers.
let value1: Int? = 1
let value2: Int? = 2
let nilValue: Int? = nil
value1 <? value2 // true
value1 <? nilValue // false
value2 != nilValue // true
value2 !=? nilValue // false
infix operator >?: NilCoalescingPrecedence
infix operator >=?: NilCoalescingPrecedence
infix operator <?: NilCoalescingPrecedence
infix operator <=?: NilCoalescingPrecedence
infix operator !=?: NilCoalescingPrecedence
public extension Optional where Wrapped: Comparable {
/// Unwraps both sides, returning `false` if either is `nil`, then performs the comparison check.
static func >? (lhs: Wrapped?, rhs: Wrapped?) -> Bool {
guard let lhs = lhs, let rhs = rhs else {
return false
}
return lhs > rhs
}
/// Unwraps both sides, returning `false` if either is `nil`, then performs the comparison check.
static func >=? (lhs: Wrapped?, rhs: Wrapped?) -> Bool {
guard let lhs = lhs, let rhs = rhs else {
return false
}
return lhs >= rhs
}
/// Unwraps both sides, returning `false` if either is `nil`, then performs the comparison check.
static func <? (lhs: Wrapped?, rhs: Wrapped?) -> Bool {
guard let lhs = lhs, let rhs = rhs else {
return false
}
return lhs < rhs
}
/// Unwraps both sides, returning `false` if either is `nil`, then performs the comparison check.
static func <=? (lhs: Wrapped?, rhs: Wrapped?) -> Bool {
guard let lhs = lhs, let rhs = rhs else {
return false
}
return lhs <= rhs
}
}
public extension Optional where Wrapped: Equatable {
/// Unwraps both sides, returning `false` if either is `nil`, then performs the equation check.
static func !=? (lhs: Wrapped?, rhs: Wrapped?) -> Bool {
guard let lhs = lhs, let rhs = rhs else {
return false
}
return lhs != rhs
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment