An "overflow" arithmetic operator in Swift

Source: Internet
Author: User

You know that Swift has arithmetic operators similar to C,OBJC, which are:

+
-
*
/
%

But you may not know that there is a big difference between the operators in Swift and the C,OBJC language that they cannot be "spilled", either overflow or underflow!

In lower-level languages such as C, if you do arithmetic on an arithmetic value that can overflow, the result is a so-called overflow or underflow, such as your maximum Int32 positive plus one result is a large negative number:-2147483648

In Swift, however, if this happens, the runtime throws an exception and your app hangs!

This may not be the result you want, but Swift itself also provides a series of "overflow" operators corresponding to the arithmetic operators, as follows:

&+
&-
&*
&/
&%

Their behavior is exactly the same as the operators in the C,OBJC, so you can use this now without incurring a run-time error:

It is worth noting, however, that these "overflow" operators do not have a compound syntax, so you cannot write like this:

var= Int32.max&+=100

An "overflow" arithmetic operator in Swift

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.