Skip to main content
The >> operator in Swift is the bitwise right shift operator. It shifts the binary representation of an integer to the right by a specified number of bit positions, discarding the bits that are shifted beyond the least significant bit (LSB).

Syntax

  • leftOperand: The integer value whose bits will be shifted.
  • rightOperand: The number of bit positions to shift.

Behavior Based on Integer Type

Swift applies different bit-level mechanics depending on whether the left operand is an unsigned or signed integer type.

Unsigned Integers (Logical Shift)

When applied to an unsigned integer (e.g., UInt8, UInt32), >> performs a logical right shift. The vacated bit positions at the most significant bit (MSB) end are strictly filled with zeros (0).

Signed Integers (Arithmetic Shift)

When applied to a signed integer (e.g., Int8, Int), >> performs an arithmetic right shift. To preserve the mathematical sign of the integer, the vacated bit positions are filled with the value of the original sign bit (the MSB).
  • If the original value is positive (sign bit is 0), it fills the vacated spaces with 0s.
  • If the original value is negative (sign bit is 1), it fills the vacated spaces with 1s.

Operand Constraints

The rightOperand must be greater than or equal to 0 and strictly less than the bit width of the leftOperand. If the right operand falls outside this range, Swift triggers a runtime crash. To safely handle shifts that may exceed the bit width without crashing, Swift provides the masking right shift operator (&>>).
Tired of Poor Swift Skills? Fix That With Deep Grasping!Learn More