Overflow refers to what happens when an operation would result in a number that is either larger or smaller than the designated amount of bits for that number may hold.
Due to the way binary arithmetic works, after a number becomes too large for its bits, the number overflows down to the smallest possible number (for the bit size) and then continues counting up from there. Similarly, when a number becomes too small, it underflows up to the largest possible number (for its bit size) and continues counting down from there.
Because this behavior is not often desired and can lead to serious security issues, the Swift arithmetic operators +
, -
, and *
will throw errors when an operation would cause an overflow or underflow. To explicitly allow overflow and underflow, use &+
, &-
, and &*
instead.
var almostTooLarge = Int.max
almostTooLarge + 1 // not allowed
almostTooLarge &+ 1 // allowed, but result will be the value of Int.min