Advanced Operators in Swift
Apart from basic operators Swift provides some advanced operators which can enhance the capability of the calculations of your Application. These are called overflow operators. These operators basically do is to overflow or underflow the value of the variables on which you apply.Unlike arithmetic operators in C, arithmetic operators in Swift do not overflow by default. Overflow behavior is trapped and reported as an error. To opt in to overflow behavior, use Swift’s second set of arithmetic operators that overflow by default, such as the overflow addition operator (
&+
). All of these overflow operators begin with an ampersand (&
).Overflow Operators
If you try to insert a number into an integer constant or variable that cannot hold that value, by default Swift reports an error rather than allowing an invalid value to be created. This behavior gives extra safety when you work with numbers that are too large or too small.
For example, the
Int32
integer type can hold any signed integer number between -
2,147,483,648 and 2,147,483,647. Trying to set an Int32
constant or variable to a number outside of this range causes an error:var integerVariable = Int32.max
// integerVariable equals 2,147,483,647, which is the largest value an Int32 can hold
integerVariable += 1
// this causes an error
Providing error handling when values get too large or too small gives you much more flexibility when coding for boundary value conditions.
However, when you specifically want an overflow condition to truncate the number of available bits, you can opt in to this behavior rather than triggering an error. Swift provides five arithmetic overflow operators that opt in to the overflow behavior for integer calculations. These operators all begin with an ampersand (
&
):- 1. Overflow addition (
&+
) - 2. Overflow subtraction (
&-
) - 3. Overflow multiplication (
&*
)4. Overflow division (&/
)5. Overflow remainder (&%
)
Overflow Example
Here’s an example of what happens when an unsigned value is allowed to overflow, using the overflow addition operator (
&+
):
var variableWillOverflow = UInt16.max
// variableWillOverflow equals 32767, which is the largest value a UInt16 can hold
variableWillOverflow = variableWillOverflow &+ 1
// variableWillOverflow is now equal to 0
Underflow Example
Numbers can also become too small to fit in their type's maximum bounds. Here is an Example:-
var variableWillunderflow = UInt16.min
// variableWillunderflow equals 0, which is the smallest value a UInt16 can hold
variableWillunderflow = variableWillunderflow &- 1
// variableWillunderflow is now equal to 32767
No comments:
Post a Comment