Skip to content

Instantly share code, notes, and snippets.

@stigi
Created March 12, 2018 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stigi/c01bb1014f0b96ec8938d1d8d29239e6 to your computer and use it in GitHub Desktop.
Save stigi/c01bb1014f0b96ec8938d1d8d29239e6 to your computer and use it in GitHub Desktop.
Safely convert Double to Int and take care of overflows. Wont take care of precision for large values. Raw
func doubleToInt(_ input: Double) -> Int? {
guard (
input < Double(Int.max).nextDown &&
input > Double(Int.min).nextDown)
else {
// Int overflow
return nil
}
return Int(input)
}
doubleToInt(Double(Int.max)) // returns nil
doubleToInt(Double(Int.max) - 1535) // returns nil
doubleToInt(Double(Int.max) - 1536) // returns 9223372036854773760
doubleToInt(Double(Int.min)) // -9223372036854775808
doubleToInt(Double(Int.min) - 1) // -9223372036854775808
doubleToInt(Double(Int.min) - 1024) // -9223372036854775808
doubleToInt(Double(Int.min) - 1025) // nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment