In Swift, what does `%` return for a negative operand such as `-7 % 3`, and why does `%` not compile on a Double?
answer
- remainder, not modulo
- sign follows the left operand
- backward index wrap goes negative
- floating point uses named methods
basics
~20 sSwift's % is a remainder, not a modulo: the result takes the left operand's sign, so -7 % 3 is -1, and the divisor's sign is ignored. Double has no %; use truncatingRemainder(dividingBy:) or the IEEE remainder(dividingBy:).
solid answer
~40 sFor integers, `%` truncates the quotient toward zero, so the result has the sign of the left operand: `-7 % 3 == -1` and `7 % -3 == 1`. That bites when wrapping an index backwards: `(i - 1) % count` is `-1` at `i == 0`, and subscripting an array with it traps, so add `count` back when the result is negative. `%` also traps on a zero divisor ("Division by zero in remainder operation") and on `Int.min % -1`. For `Double` and `Float`, `%` is unavailable, with the message "For floating point numbers use truncatingRemainder instead". `truncatingRemainder(dividingBy:)` follows the same truncating rule, while `remainder(dividingBy:)` is the IEEE 754 remainder, which rounds the quotient to nearest and can return a negative value for positive inputs.
code
swift · 17 lineslet slots = ["A", "B", "C", "D"]
let current = 0
func previous(_ i: Int) -> Int {
(i - 1) % slots.count // -1 when i == 0
}
func previousWrapped(_ i: Int) -> Int {
let r = (i - 1) % slots.count
return r < 0 ? r + slots.count : r // 3 when i == 0
}
print(-7 % 3, 7 % -3, -7 % -3) // -1 1 -1
print(previous(current)) // -1: slots[-1] would trap
print(slots[previousWrapped(current)]) // D
print((-7.5).truncatingRemainder(dividingBy: 2)) // -1.5
print((-7.5).remainder(dividingBy: 2)) // 0.5go deeper
Recall that % is a remainder whose sign follows the left operand, and that Double needs truncatingRemainder(dividingBy:) instead.
Explain truncation toward zero, why a % -b equals a % b, the zero-divisor and Int.min % -1 traps, and how the two floating-point methods differ.
Spot the backward-wrap bug in ring buffers and carousels before it ships, and fix it by adding the divisor back rather than guarding every call site.
Where circular indexing recurs, have the team share one tested wrapping helper so the negative-remainder rule is solved once, not rediscovered per feature.
## Remainder, not modulo Swift's `%` is the **remainder operator**. For integers, `a % b` is what is left after dividing `a` by `b` with the quotient **truncated toward zero**, so it satisfies `a == b * (a / b) + a % b`. The standard library's doc comment states the consequence: the result has the same sign as the left operand and a magnitude less than the right operand's magnitude. | Expression | Result | Why | |---|---|---| | `9 % 4` | `1` | 9 = 4 × 2 + 1 | | `-9 % 4` | `-1` | -9 = 4 × -2 + -1 | | `-7 % 3` | `-1` | the sign follows the left operand | | `7 % -3` | `1` | the right operand's sign is ignored | | `-7 % -3` | `-1` | the sign still follows the left operand | The Swift book makes the same point: `%` is called a modulo operator in some languages, but because of how it treats negative numbers it is, strictly speaking, a remainder. A mathematical modulo with a positive divisor always lands in `0..<n`; Swift's `%` can be negative. ## Where it bites: wrapping an index backwards Circular structures, such as a carousel, a ring buffer or the previous player in a turn order, often compute a neighbour with `%`. Moving forward is fine, because `(i + 1) % count` is never negative for a non-negative `i`. Moving backward is not: - At `i == 0`, `(i - 1) % count` is `-1`. - Subscripting an array with `-1` traps with `Array index is out of range`. The fix is to add the divisor back when the remainder is negative: 1. compute `r = (i - 1) % count`; 2. if `r < 0`, use `r + count`; 3. otherwise use `r`. The one-line form `((a % n) + n) % n` does the same for a positive `n`. The code example shows both behaviours side by side. ## Integer edge cases that trap `%` shares division's failure modes: - A zero right operand traps with `Division by zero in remainder operation`; with literals, the compiler rejects it at build time. - `Int.min % -1` traps with `Division results in an overflow in remainder operation`, because the matching quotient does not fit in `Int`. - `remainderReportingOverflow(dividingBy:)` returns `(partialValue, overflow)` instead of trapping, for code that must handle these cases. ## Floating point: no % at all For `Double` and `Float`, `%` is declared unavailable. Writing `7.5 % 2` fails with the message `'%' is unavailable: For floating point numbers use truncatingRemainder instead`. Two methods replace it, and they are different operations: - `truncatingRemainder(dividingBy:)` truncates the quotient toward zero, like integer `%`: `(-7.5).truncatingRemainder(dividingBy: 2)` is `-1.5`, with the sign of the left operand. - `remainder(dividingBy:)` is the IEEE 754 remainder: it rounds the quotient to the nearest integer, so the result can be negative even for positive inputs. `(7.5).remainder(dividingBy: 2)` is `-0.5`, and `(-7.5).remainder(dividingBy: 2)` is `0.5`. Pick `truncatingRemainder(dividingBy:)` when porting integer-style logic such as "seconds past the minute"; pick `remainder(dividingBy:)` when you want the value closest to zero, such as reducing an angle into a symmetric interval. ## Related arithmetic rules - `%` sits in `MultiplicationPrecedence` with `*` and `/`, so `a + b % c` is `a + (b % c)`. - Compound assignment such as `i %= n` or `i += 1` returns no value, so `let b = a += 2` does not compile. - There is no `++` or `--` in today's Swift: they were removed in Swift 3, and `i++` now fails with `cannot find operator '++' in scope; did you mean '+= 1'?`.
- How do you get a result in `0..<n` for any integer `a` and positive `n`?Add the divisor back when the remainder is negative: `let r = a % n; let m = r < 0 ? r + n : r`, or the one-liner `((a % n) + n) % n`. Both give 3 for `a == -1, n == 4`. Swift's standard library has no separate modulo operator, so this is written by hand.
- When would you pick `remainder(dividingBy:)` over `truncatingRemainder(dividingBy:)` for a Double?`remainder(dividingBy:)` rounds the quotient to the nearest integer, so the result is the value of smallest magnitude, which suits reducing an angle into a symmetric interval around zero. `truncatingRemainder(dividingBy:)` truncates toward zero like integer `%`, which suits time arithmetic such as seconds past the minute.
- Swift's % always returns a non-negative result, like mathematical modulo
- -7 % 3 evaluates to 2 in Swift
- Writing a % -b flips the sign of the result
- % works on Double exactly as it does on Int
- remainder(dividingBy:) and truncatingRemainder(dividingBy:) are two names for one operation