Get the distance between UInt64 values

Updated
Mar 10, 2020 1:41 PM
Created
Mar 10, 2020 1:34 PM
Tags
Swift
Keywords

What if, we need to get the distance value between UInt64 values.

Following case would works fine.

let distance = UInt64(2) - UInt64(1)

But, how about this case?

This code case overflow.

let distance = UInt64(1) - UInt64(2)

In Swift, we can use .distance method to get the distance value.

UInt64(2).distance(to: UInt64(1)) // -1
UInt64(1).distance(to: UInt64(2)) // 1