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 in Swift is the bitwise OR operator. It performs a logical inclusive OR operation on the individual binary bits of two integer values. It evaluates the operands bit-by-bit and returns a new integer of the same type, where each bit is set to 1 if the corresponding bit in either or both of the operands is 1. If both corresponding bits are 0, the resulting bit is 0.

Syntax

The operator is an infix operator placed between two integer operands of the exact same type.
let result = operand1 | operand2

Bitwise Evaluation Mechanics

The operator follows a standard truth table for each bit position:
  • 0 | 0 evaluates to 0
  • 0 | 1 evaluates to 1
  • 1 | 0 evaluates to 1
  • 1 | 1 evaluates to 1

Code Visualization

To observe the mechanical behavior, it is best to use explicitly typed unsigned integers (like UInt8) and binary literals (0b prefix).
let a: UInt8 = 0b10100011 // Decimal: 163
let b: UInt8 = 0b01011010 // Decimal: 90

let c = a | b             // Decimal: 251
Bit-by-bit execution:
  10100011  (Operand a)
| 01011010  (Operand b)

  11111011  (Result c)

Type Constraints

Swift enforces strict type safety. The | operator cannot implicitly bridge different integer types or sizes. Both operands must be of the exact same type, and the return type will match the operands.
let x: UInt8 = 0b00001111
let y: UInt16 = 0b11110000

// let z = x | y // Compiler Error: Binary operator '|' cannot be applied to operands of type 'UInt8' and 'UInt16'
let z = UInt16(x) | y // Valid: Both are now UInt16

Compound Assignment

Swift provides the |= compound assignment operator, which performs the bitwise OR operation and assigns the result directly back to the left-hand operand. The left-hand operand must be a mutable variable (var).
var register: UInt8 = 0b00000000
register |= 0b00001111 
// register is now 0b00001111

register |= 0b11110000 
// register is now 0b11111111
Master Swift with Deep Grasping Methodology!Learn More