The remainder %
Swift operator calculates the remainder of the integer division:
a % b = a - (a/b) * b
where /
is a division with truncation of integers. In your case
(-1) % 3 = (-1) - ((-1)/3) * 3 = (-1) - 0 * 3 = -1
Thus, the balance always has the same sign as the dividend (if only the balance is zero).
This is the same definition as required, for example. in the C99 standard; see, for example, Does ANSI C or ISO C indicate -5% 10? . See also Wikipedia: Modulo operation for an overview of how it is handled in different programming languages.
The true module function can be defined in Swift as follows:
func mod(_ a: Int, _ n: Int) -> Int { precondition(n > 0, "modulus must be positive") let r = a % n return r >= 0 ? r : r + n } print(mod(-1, 3))
source share