TIL Overflow operators in Swift language guide
Innocent code i += 1
. What might be wrong with it? Definately, overflow. In Objective-C developer should anticipate where overflow might happen. Otherwise it just happens silently:
Equal Swift code doesn’t even compile. Compiler is smart enough to detect overflow here:
When value isn’t available in source code compiler isn’t that helpful.
The truth is these snippets are not equal. Objective-C as well as C doesn’t care about overflow. It’s burden of developer to anticipate possible overflow and deal with it. Swift, contrary, raises exception on overflow in arithmentic operations. And this code is not throwable, exception can’t be cought.
App just crashes on overflow. That’s main difference between similar looking Objective-C code:
Swift code behaving similar to one in Objective-C is looking like below. These operators are called in Swift language guide overflow operators.
What are not reflected in Swift language guide are arithmetic operations with reporting overflow:
It might be interesting interview question to ask if there any difference in behaviour of operator i += 1
in Swift and Objective-C.