Skip to main content
The << (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:
  1. Displacement: Every bit in the leftOperand is moved to the left by the number of positions defined by the rightOperand.
  2. Zero Extension: The vacated bit positions on the least significant bit (LSB) side (the right side) are filled with zeros.
  3. 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 to 0. 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.
Note: This behavior distinguishes << 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 BinaryInteger protocol. However, they are not required to be the exact same type. The right-hand operand (RHS) can be any type conforming to BinaryInteger, allowing you to shift an Int64 by an Int8, for example.

Bitwise Visualization

The following demonstrates the mechanical shift of an 8-bit unsigned integer:
The following demonstrates Swift’s smart shift handling of out-of-bounds and negative values:

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.
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More