Swift Remainder Operator: Why -9 % 4 Returns -1
Understand Swift's remainder operator behavior with negative numbers and why it differs from modulo.
Swift Remainder Operator: Why -9 % 4 Returns -1
Swift’s % operator behaves differently with negative numbers than you might expect.
The Question
1
2
9 % 4 // What does this return?
-9 % 4 // What about this?
The Answer
1
2
9 % 4 // = 1
-9 % 4 // = -1
Why It Works This Way
The formula: a = (b × multiplier) + remainder
For 9 % 4:
1
9 = (4 × 2) + 1
For -9 % 4:
1
-9 = (4 × -2) + -1
The remainder keeps the sign of the dividend (left side).
Remainder vs Modulo
Swift calls % the remainder operator, not modulo. They differ with negative numbers:
| Expression | Swift Remainder | Mathematical Modulo |
|---|---|---|
9 % 4 | 1 | 1 |
-9 % 4 | -1 | 3 |
The Divisor Sign Is Ignored
1
2
-9 % 4 // = -1
-9 % -4 // = -1 (same result)
The sign of the right operand has no effect on the result.
Getting True Modulo Behavior
If you need mathematical modulo (always positive result):
1
2
3
4
5
6
func mod(_ a: Int, _ n: Int) -> Int {
let r = a % n
return r >= 0 ? r : r + abs(n)
}
mod(-9, 4) // = 3
☕ Support My Work
If you found this post helpful and want to support more content like this, you can buy me a coffee!
Your support helps me continue creating useful articles and tips for fellow developers. Thank you! 🙏
This post is licensed under CC BY 4.0 by the author.