Skip to content

Instantly share code, notes, and snippets.

@xsleonard
Created May 22, 2020 10:41
Show Gist options
  • Save xsleonard/e4481506896763cb59a84d63a789888f to your computer and use it in GitHub Desktop.
Save xsleonard/e4481506896763cb59a84d63a789888f to your computer and use it in GitHub Desktop.
Distance between Int64 in Swift
extension Int64 {
/*
Returns the absolute distance between two Int64 values as a UInt64.
A UInt64 is required to represent the range of possible distance values.
*/
func distanceTo(_ other: Int64) -> UInt64 {
if self == other {
return 0
}
if self > other {
return other.distanceTo(self)
}
let (distance, overflow) = other.subtractingReportingOverflow(self)
if !overflow {
return UInt64(distance)
}
// Int64.max minus any negative Int64 is too large to fit into an Int64. Convert it to a Uint64.
// Take the difference between 0 and the negative number and add it to positive number, as UInt64
let lowerDistance = self == Int64.min ? UInt64(Int64.max) + 1 : UInt64(-self)
return lowerDistance + UInt64(other)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment