Skip to content

Instantly share code, notes, and snippets.

@NikolajMosbaek
Created June 7, 2022 12:05
Show Gist options
  • Save NikolajMosbaek/65d2c3904ba73e401cf1dfc7c6f4d1b2 to your computer and use it in GitHub Desktop.
Save NikolajMosbaek/65d2c3904ba73e401cf1dfc7c6f4d1b2 to your computer and use it in GitHub Desktop.
This is how you can create the spaceship operator found in many other programming languages
infix operator <=>
func <=><T: Comparable>(lhs: T, rhs: T) -> ComparisonResult {
if lhs < rhs { return .orderedAscending}
if lhs > rhs { return .orderedDescending }
return .orderedSame
}
@NikolajMosbaek
Copy link
Author

@NikolajMosbaek
Copy link
Author

NikolajMosbaek commented Jun 7, 2022

Usage:

let left = 5
let right = 6
let result = left <=> right
print(result.rawValue)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment