


Overflow Multiply operator computes multiplication. Here’s an example of what happens when an Int16 is allowed to overflow, using the overflow subtract operator (&-): var int16Overflow = Int16.min // -32768 Subtraction result can overflow in both the positive and negative direction. Overflow Subtract operator computes subtraction. Here’s an example of what happens when an Int16 is allowed to overflow, using the overflow add operator (&+): var int16Overflow = Int16.max PotentialOverflow = potentialOverflow + 1 // this causes an error Trying to set an Int16 constant or variable to a number outside of this range causes an error: var potentialOverflow = Int16.max Addition result can overflow in both the positive and negative direction.Īrithmetic operators ( +, -, *, /, % and so forth) detect and disallow value overflow, to avoid unexpected results when working with numbers that become larger or smaller than the allowed value range of the type that stores them.įor example, the Int16 integer type can hold any signed integer between -3277. Remainder operator computes remainder after division. let num1 = 10ĭivide operator computes division. Multiply operator computes multiplication. Let shiftBits: UInt8 = 4 // 00000100 in binaryĪdd operator computes addition. Bitwise right shifts have the effect of dividing an integer by a factor of two.The bitwise right shift operator (>) move all bits in a number to the right by a certain number of places, according to the rules defined below. The sign of a numeric value can be toggled using a prefixed -, known as the unary minus operator.
#Swift downcast vs cast code
let minusSix = -6Īlthough the unary plus operator doesn’t actually do anything, we can use it to provide symmetry in your code for positive numbers when also using the unary minus operator for negative numbers. The unary plus operator (+) simply returns the value it operates on, without any change. Let invertedBits = ~initialBits // equals 11110000 The bitwise NOT operator (~) inverts all bits in a number. The logical NOT operator (!) inverts a Boolean value so that true becomes false, and false becomes true. The tables below list the operators declared in Swift. Like, the assignment operator ( =) doesn’t return a value, to prevent it from being mistakenly used when the equal to operator ( =) is intended. Swift supports most standard C operators and improves several capabilities to eliminate common coding errors. For example, the addition operator ( +) adds two numbers, as in let i = 1 + 2. An operator is a special symbol or phrase that you use to check, change, or combine values.
