Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Created October 31, 2018 14:40
Show Gist options
  • Save alexpaul/05a178904960bb2ba4821ca381826dc8 to your computer and use it in GitHub Desktop.
Save alexpaul/05a178904960bb2ba4821ca381826dc8 to your computer and use it in GitHub Desktop.
Checking for overflow arithmetic operations in Swift, e.g adding to Int.max and subtracting from Int.min
// Apple Documentation: https://developer.apple.com/documentation/swift/uint64/2885895-addingreportingoverflow
let intMin = Int.min // -9223372036854775808
let intMax = Int.max // 9223372036854775807
print(intMin)
print(intMax)
if case let (result, overflow) = intMax.addingReportingOverflow(1), !overflow {
print(result)
} else {
print("overflow while trying to add to Int.max")
}
if case let (result, overflow) = intMin.subtractingReportingOverflow(1), !overflow {
print(result)
} else {
print("overflow detected while subtracting from Int.min")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment