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.
% operator in Swift is the remainder operator, which calculates the integer remainder after dividing one number (the dividend) by another (the divisor). Unlike a strict mathematical modulo operator found in some other languages, Swift’s % operator computes the remainder using truncating division. This means the sign of the result is determined strictly by the dividend, while the sign of the divisor is ignored.
Syntax and Underlying Equation
% operator satisfies the following equation, where multiplier is the quotient (the number of times b fits into a using truncating division), and (b * multiplier) represents the actual multiple:
a = (b * multiplier) + remainder
Integer Evaluation
The operator evaluates the operands and returns the exact integer left over.Handling of Negative Operands
Because Swift uses truncating division, the remainder will always carry the sign of the left-hand operand (a). The sign of the right-hand operand (b) is entirely disregarded during the calculation.
Type Constraints
The% operator is strictly constrained to integer types (e.g., Int, Int8, UInt64). Attempting to use the % operator on floating-point types (Double, Float, CGFloat) will result in a compile-time error.
To achieve the equivalent mathematical operation on floating-point numbers, Swift requires the use of the truncatingRemainder(dividingBy:) instance method. When demonstrating this, it is best to use values with exact binary representations to avoid standard IEEE 754 floating-point precision artifacts.
Division by Zero
Like the standard division operator (/), passing 0 as the right-hand operand to the % operator is an illegal operation. Doing so will trigger a runtime trap (crash) rather than returning nil or NaN.
If the divisor is a constant (let) known at compile time, Swift’s constant folding will catch the operation and emit a compile-time error. To observe the runtime trap, the divisor’s value must be evaluated at runtime (e.g., using a var or a dynamically passed argument).
Master Swift with Deep Grasping Methodology!Learn More





