Overflow operators
Swift, at its core, is designed for safety. One of these safety mechanisms is the inability to insert a number into a variable when the variable type is too small to hold it. As an example, the following code will throw the following error: arithmetic operation '255 + 1' (on type 'UInt8') results in an overflow
:
let b: UInt8 = UInt8.max +1
The reason an error is thrown is we are trying to add one to the maximum number that a UInt8
can hold. This error checking can help prevent unexpected and hard-to-trace issues in our applications. Let's take a second and look at what would happen if Swift did not throw an error when an overflow occurs. In a UInt8
variable, which is an 8-bit unsigned integer, the number 255 is stored like this, where all of the bits are set to 1:
Figure 15.8: The binary representation of 255
Now if we add 1 to this number, the new number will be stored like this:
Figure 15.9: Overflow when...