Created
March 12, 2018 20:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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