Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The |= operator is the bitwise OR assignment operator in Swift. It is a compound assignment operator that performs a bitwise OR operation (|) between two integer operands and assigns the resulting value back to the left-hand operand.
lhs |= rhs

Mechanics

The operator evaluates the binary representations of both operands. It compares the bits at each corresponding position and applies the following logic:
  • If the bit in either the left-hand operand OR the right-hand operand is 1, the resulting bit is set to 1.
  • If the bits in both operands are 0, the resulting bit is set to 0.
Because it is an assignment operator, the left-hand side (lhs) must be a mutable variable (var), while the right-hand side (rhs) can be a variable, constant, or literal.

Syntax and Evaluation

var a: UInt8 = 0b0000_1100 // Decimal 12
let b: UInt8 = 0b0000_1010 // Decimal 10

a |= b 

// 'a' is mutated to 0b0000_1110 (Decimal 14)
Bit-level execution:
  0000 1100  (lhs: 12)
| 0000 1010  (rhs: 10)

  0000 1110  (result: 14 assigned back to lhs)

Type Constraints and Semantics

  1. Protocol Conformance: Both operands must conform to the BinaryInteger protocol. This includes standard library integers (e.g., Int, UInt8, Int64) as well as custom arbitrary-precision integers. The operator cannot be applied to floating-point types.
  2. Strict Type Matching: Swift enforces strict type safety. The lhs and rhs must be of the exact same integer type. Swift will not implicitly cast a UInt8 to an Int to perform the operation; explicit initialization is required if the types differ.
  3. Evaluation Semantics: The expression a |= b produces the same logical result as a = a | b, but with a critical distinction in evaluation: the compound assignment operator evaluates the left-hand side expression only once. This is highly relevant when the left-hand side is a computed property, a function returning an inout reference, or an array subscript.
  4. Thread Safety: The |= operator performs a non-atomic read-modify-write sequence. It is not thread-safe and should not be treated as an atomic operation in concurrent contexts.
Master Swift with Deep Grasping Methodology!Learn More