Last active
October 20, 2020 03:50
-
-
Save rl-pavel/276adc678c1ddabac3f179212f1e95c1 to your computer and use it in GitHub Desktop.
Optional Comparable and Equatable helpers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let value1: Int? = 1 | |
let value2: Int? = 2 | |
let nilValue: Int? = nil | |
value1 <? value2 // true | |
value1 <? nilValue // false | |
value2 != nilValue // true | |
value2 !=? nilValue // false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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