Created
October 31, 2018 14:40
-
-
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
This file contains hidden or 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
| // 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