the-swift-rogramming-language
.pdf
let lastSixBits: UInt8 = 0b00111111
let middleFourBits = firstSixBits & lastSixBits // equals 00111100
Bitwise OR Operator
The bitwise OR operator (|) compares the bits of two numbers. The operator returns a new number whose bits are set to 1 if the bits are equal to 1 in either input number:
In the example below, the values of someBits and moreBits have different bits set to 1. The bitwise OR operator combines them to make the number 11111110, which equals an unsigned decimal of 254:
let someBits: UInt8 = 0b10110010 let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits // equals 11111110
Bitwise XOR Operator
The bitwise XOR operator, or “exclusive OR operator” (^), compares the bits of two numbers. The operator returns a new number whose bits are set to 1 where the input bits are different and are set to 0 where the input bits are the same:
In the example below, the values of firstBits and otherBits each have a bit set to 1 in a location that the other does not. The bitwise XOR operator sets both of these bits to 1 in its output value. All of the other bits in firstBits and otherBits match and are set to 0 in the output value:
let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits // equals 00010001
Bitwise Left and Right Shift Operators
The bitwise left shift operator (<<) and bitwise right shift operator (>>) move all bits in a number to the left or the right by a certain number of places, according to the rules defined below.
Bitwise left and right shifts have the effect of multiplying or dividing an integer number by a factor of two. Shifting an integer’s bits to the left by one position doubles its value, whereas shifting it to the right by one position halves its value.
Shifting Behavior for Unsigned Integers
The bit-shifting behavior for unsigned integers is as follows:
1.Existing bits are moved to the left or right by the requested number of places.
2.Any bits that are moved beyond the bounds of the integer’s storage are discarded.
3.Zeroes are inserted in the spaces left behind after the original bits are moved to the left or right.
This approach is known as a logical shift.
The illustration below shows the results of 11111111 << 1 (which is 11111111 shifted to the left by 1 place), and 11111111 >> 1 (which is 11111111 shifted to the right by 1 place). Blue numbers are shifted, gray numbers are discarded, and orange zeroes are inserted:
Here’s how bit shifting looks in Swift code:
let shiftBits: UInt8 = 4 shiftBits << 1 shiftBits << 2 shiftBits << 5 shiftBits << 6 shiftBits >> 2
//00000100 in binary
//00001000
//00010000
//10000000
//00000000
//00000001
You can use bit shifting to encode and decode values within other data types:
let |
pink: UInt32 = 0xCC6699 |
|
|
let |
redComponent = (pink & 0xFF0000) >> 16 |
// redComponent is 0xCC, or 204 |
|
let |
greenComponent = (pink & 0x00FF00) >> 8 |
// greenComponent is 0x66, or 102 |
|
let |
blueComponent = pink & 0x0000FF |
// blueComponent is 0x99, or 153 |
|
|
|
|
|
This example uses a UInt32 constant called pink to store a Cascading Style Sheets color value for the color pink. The CSS color value #CC6699 is written as 0xCC6699 in Swift’s hexadecimal number representation. This color is then decomposed into its red (CC), green (66), and blue (99) components by the bitwise AND operator (&) and the bitwise right shift operator (>>).
The red component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0xFF0000. The zeroes in 0xFF0000 effectively “mask” the second and third bytes of 0xCC6699, causing the 6699 to be ignored and leaving 0xCC0000 as the result.
This number is then shifted 16 places to the right (>> 16). Each pair of characters in a hexadecimal number uses 8 bits, so a move 16 places to the right will convert 0xCC0000 into 0x0000CC. This is the same as 0xCC, which has a decimal value of 204.
Similarly, the green component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0x00FF00, which gives an output value of 0x006600. This output value is then shifted eight places to the right, giving a a value of 0x66, which has a decimal value of 102.
Finally, the blue component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0x0000FF, which gives an output value of 0x000099. There’s no need to shift this to the right, as 0x000099 already equals 0x99, which has a decimal value of 153.
Shifting Behavior for Signed Integers
The shifting behavior is more complex for signed integers than for unsigned integers, because of the way signed integers are represented in binary. (The examples below are based on 8-bit signed integers for simplicity, but the same principles apply for signed integers of any size.)
Signed integers use their first bit (known as the sign bit) to indicate whether the integer is positive or negative. A sign bit of 0 means positive, and a sign bit of 1 means negative.
The remaining bits (known as the value bits) store the actual value. Positive numbers are stored in exactly the same way as for unsigned integers, counting upwards from 0. Here’s how the bits inside an Int8 look for the number 4:
The sign bit is 0 (meaning “positive”), and the seven value bits are just the number 4, written in binary notation.
Negative numbers, however, are stored differently. They are stored by subtracting their absolute value from 2 to the power of n, where n is the number of value bits. An eight-bit number has seven value bits, so this means 2 to the power of 7, or 128.
Here’s how the bits inside an Int8 look for the number -4:
This time, the sign bit is 1 (meaning “negative”), and the seven value bits have a binary
value of 124 (which is 128 - 4):
The encoding for negative numbers is known as a two’s complement representation. It may seem an unusual way to represent negative numbers, but it has several advantages.
First, you can add -1 to -4, simply by performing a standard binary addition of all eight bits (including the sign bit), and discarding anything that doesn’t fit in the eight bits once you’re done:
Second, the two’s complement representation also lets you shift the bits of negative numbers to the left and right like positive numbers, and still end up doubling them for every shift you make to the left, or halving them for every shift you make to the right. To achieve this, an extra rule is used when signed integers are shifted to the right:
When you shift signed integers to the right, apply the same rules as for unsigned integers, but fill any empty bits on the left with the sign bit, rather than with a zero.
This action ensures that signed integers have the same sign after they are shifted to the right, and is known as an arithmetic shift.
Because of the special way that positive and negative numbers are stored, shifting either of them to the right moves them closer to zero. Keeping the sign bit the same during this
shift means that negative integers remain negative as their value moves closer to zero.
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 Int16 integer type can hold any signed integer number between -32768 and 32767. Trying to set a UInt16 constant or variable to a number outside of this range causes an error:
var potentialOverflow = Int16.max
//potentialOverflow equals 32767, which is the largest value an Int16 can hold potentialOverflow += 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 (&):
Overflow addition (&+)
Overflow subtraction (&-)
Overflow multiplication (&*)
Overflow division (&/)
Overflow remainder (&%)
Value Overflow
Here’s an example of what happens when an unsigned value is allowed to overflow, using the overflow addition operator (&+):
var willOverflow = UInt8.max
//willOverflow equals 255, which is the largest value a UInt8 can hold willOverflow = willOverflow &+ 1
//willOverflow is now equal to 0
The variable willOverflow is initialized with the largest value a UInt8 can hold (255, or 11111111 in binary). It is then incremented by 1 using the overflow addition operator (&+). This pushes its binary representation just over the size that a UInt8 can hold, causing it to overflow beyond its bounds, as shown in the diagram below. The value that remains within the bounds of the UInt8 after the overflow addition is 00000000, or zero:
Value Underflow
Numbers can also become too small to fit in their type’s maximum bounds. Here’s an example.
The smallest value that a UInt8 can hold is 0 (which is 00000000 in eight-bit binary form). If you subtract 1 from 00000000 using the overflow subtraction operator, the number will overflow back round to 11111111, or 255 in decimal:
Here’s how that looks in Swift code:
var willUnderflow = UInt8.min
// willUnderflow equals 0, which is the smallest value a UInt8 can hold
willUnderflow = willUnderflow &- 1
// willUnderflow is now equal to 255
A similar underflow occurs for signed integers. All subtraction for signed integers is performed as straight binary subtraction, with the sign bit included as part of the numbers being subtracted, as described in Bitwise Left and Right Shift Operators. The smallest number that an Int8 can hold is -128, which is 10000000 in binary. Subtracting 1 from this binary number with the overflow operator gives a binary value of 01111111, which toggles the sign bit and gives positive 127, the largest positive value that an Int8 can hold:
Here’s the same thing in Swift code:
var signedUnderflow = Int8.min
//signedUnderflow equals -128, which is the smallest value an Int8 can hold signedUnderflow = signedUnderflow &- 1
//signedUnderflow is now equal to 127
The end result of the overflow and underflow behavior described above is that for both signed and unsigned integers, overflow always wraps around from the largest valid integer value back to the smallest, and underflow always wraps around from the smallest value to the largest.
Division by Zero
Dividing a number by zero (i / 0), or trying to calculate remainder by zero (i % 0), causes an error:
let x = 1
let y = x / 0
However, the overflow versions of these operators (&/ and &%) return a value of zero if you divide by zero:
let x = 1
let y = x &/ 0
// y is equal to 0
Precedence and Associativity
Operator precedence gives some operators higher priority than others; these operators are calculated first.
Operator associativity defines how operators of the same precedence are grouped together (or associated)—either grouped from the left, or grouped from the right. Think of it as meaning “they associate with the expression to their left,” or “they associate with the expression to their right.”
It is important to consider each operator’s precedence and associativity when working out the order in which a compound expression will be calculated. Here’s an example. Why does the following expression equal 4?
2 + 3 * 4 % 5
// this equals 4
Taken strictly from left to right, you might expect this to read as follows:
2 plus 3 equals 5;
5 times 4 equals 20;
20 remainder 5 equals 0
However, the actual answer is 4, not 0. Higher-precedence operators are evaluated before lower-precedence ones. In Swift, as in C, the multiplication operator (*) and the remainder operator (%) have a higher precedence than the addition operator (+). As a result, they are both evaluated before the addition is considered.
However, multiplication and remainder have the same precedence as each other. To work out the exact evaluation order to use, you also need to consider their associativity. Multiplication and remainder both associate with the expression to their left. Think of this as adding implicit parentheses around these parts of the expression, starting from their left:
2 + ((3 * 4) % 5)
(3 * 4) is 12, so this is equivalent to:
2 + (12 % 5)
(12 % 5) is 2, so this is equivalent to:
2 + 2
This calculation yields the final answer of 4.
For a complete list of Swift operator precedences and associativity rules, see Expressions.
N O T E
Swift’s operator precedences and associativity rules are simpler and more predictable than those found in C and Objective-C. However, this means that they are not the same as in C-based languages. Be careful to ensure that operator interactions still behave in the way you intend when porting existing code to Swift.
Operator Functions
Classes and structures can provide their own implementations of existing operators. This is known as overloading the existing operators.
The example below shows how to implement the arithmetic addition operator (+) for a custom structure. The arithmetic addition operator is a binary operator because it operates on two targets and is said to be infix because it appears in between those two targets.
The example defines a Vector2D structure for a two-dimensional position vector (x, y), followed by a definition of an operator function to add together instances of the Vector2D structure:
struct Vector2D {
var x = 0.0, y = 0.0
}
@infix func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y)
