TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
<< (bitwise left shift) operator shifts all bits in an integer’s binary representation to the left by a specified number of positions. In Swift, << implements “smart shift” semantics, safely handling over-shifting and negative shift amounts without triggering runtime traps or undefined behavior.
Technical Mechanics
When the<< operator is applied, it performs the following bit-level operations:
- Displacement: Every bit in the
leftOperandis moved to the left by the number of positions defined by therightOperand. - Zero Extension: The vacated bit positions on the least significant bit (LSB) side (the right side) are filled with zeros.
- Truncation: Any bits shifted beyond the bounds of the most significant bit (MSB) for the integer’s specific type width (e.g., beyond the 8th bit in a
UInt8) are permanently discarded.
Smart Shift Semantics
Unlike languages that strictly enforce shift bounds or exhibit undefined behavior on out-of-bounds shifts, Swift’s<< operator safely evaluates any integer passed as the rightOperand:
- Over-shifting: If the shift amount is greater than or equal to the bit width of the
leftOperand, the operator evaluates to0. All original bits are safely shifted out of bounds. - Negative Shifting: If the shift amount is less than
0, the operator reverses direction. A negative left shift safely performs a right shift (>>) by the absolute value of the shift amount.
<< from Swift’s masking left shift operator (&<<), which wraps the shift amount using modulo arithmetic based on the type’s bit width rather than evaluating to 0 or reversing direction.
Syntax and Type Constraints
- Return Type: The resulting value retains the exact type of the
leftOperand(Self). - Protocol Conformance: Both operands must conform to the
BinaryIntegerprotocol. However, they are not required to be the exact same type. The right-hand operand (RHS) can be any type conforming toBinaryInteger, allowing you to shift anInt64by anInt8, for example.
Bitwise Visualization
The following demonstrates the mechanical shift of an 8-bit unsigned integer:Signed Integer Behavior
The<< operator manipulates the raw bit pattern regardless of whether the integer type is signed or unsigned. When applied to signed integers (e.g., Int8), the shift does not preserve the sign bit. If a 1 is shifted into the MSB (the sign bit in two’s complement representation), the logical value of the integer will invert from positive to negative.
Master Swift with Deep Grasping Methodology!Learn More





