Skip to content

Instantly share code, notes, and snippets.

@loganblevins
Created October 18, 2024 19:25
Show Gist options
  • Save loganblevins/bf3de415246fc4a4a6bf91733b3b9956 to your computer and use it in GitHub Desktop.
Save loganblevins/bf3de415246fc4a4a6bf91733b3b9956 to your computer and use it in GitHub Desktop.
extension Double {
func safeInt() -> Int? {
guard isFinite else { return nil }
if self >= Double(Int.min) && self < Double(Int.max) {
return Int(self)
} else {
return nil
}
}
}
@loganblevins
Copy link
Author

loganblevins commented Oct 18, 2024

like: https://stackoverflow.com/a/40544010 with addition of isFinite (which checks for NaN and infinity)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment