Home > Software engineering >  Convert double into UInt64
Convert double into UInt64

Time:09-10

I have a variable that I store as a double (I use it in withAnimation). I want to use the same variable in Task.sleep but it uses nanoseconds instead and wants a UInt64. How do I convert a double into a UInt64?

CodePudding user response:

Check the docs... https://developer.apple.com/documentation/swift/uint64

let uint = UInt(myDouble)

CodePudding user response:

If your Double represents time in seconds, then you need to convert to nanoseconds (1 second = 1e9 nanoseconds) and convert to UInt64 while avoiding possible crashes. Here is a function that will do that:

func convertTimeToNanoseconds(seconds: Double) -> UInt64 {
    guard seconds > 0 else { return 0 }

    let oneSecond = 1e9  // nanoseconds
    let maxTime = Double(UInt64.max)/oneSecond
    guard seconds < maxTime else { return UInt64.max }

    return UInt64(seconds * oneSecond)
}

Tests:

print(convertTimeToNanoseconds(seconds: 123))
print(convertTimeToNanoseconds(seconds: -1))
print(convertTimeToNanoseconds(seconds: 1e50))

Output:

123000000000
0
18446744073709551615

Alternative: Return nil for bad values

func convertTimeToNanoseconds(seconds: Double) -> UInt64? {
    guard seconds > 0 else { return nil }

    let oneSecond = 1e9  // nanoseconds
    let maxTime = Double(UInt64.max)/oneSecond
    guard seconds < maxTime else { return nil }

    return UInt64(seconds * oneSecond)
}

In this case, you’d have to safely unwrap the values returned from the function.

  • Related