Like many other languages, the Swift programming language defines an operator to calculate the remainder of a division. This is convenient and it works as advertised. Most developers wrongly assume Swift's remainder operator is identical to a modulo operator in other languages. This isn't entirely accurate, though. Let's take a look at the basics first.
How Does It Work?
As always, fire up Xcode and create a playground to follow along. There is no better way to learn how to code than by writing code.
let numberOfEggs = 34
let numberOfEggsPerBox = 5
We define a constant, numberOfEggs
, and assign the value 34
to it. We define another constant, numberOfEggsPerBox
, and assign the value 5
to it. We use the division operator to calculate how many full boxes of eggs we have.
let numberOfEggs = 34
let numberOfEggsPerBox = 5
// Division Operator
numberOfEggs / numberOfEggsPerBox // 6
We use the remainder operator to calculate how many eggs are in the last box, the box that isn't full. In other words, the remainder operator returns the remainder of a division of two integers.
let numberOfEggs = 34
let numberOfEggsPerBox = 5
// Remainder Operator
numberOfEggs % numberOfEggsPerBox // 4
Be Careful
Because the remainder operator performs a division, the right operand (numberOfEggsPerBox
in the example) should not be equal to 0
. A division by zero is not allowed and results in a runtime error.
4 % 0 // Runtime Error
Does Swift Have a Modulo Operator?
Swift's remainder operator isn't the same as the modulo operator you find in other languages. The remainder operator returns the remainder of a division. This becomes clear if we have a negative number as the left operand.
-15 % 2 // -1
Is this confusing? Take a look at the following example.
// Division
let multiplier = -15 / 2 // -7
// Remainder
let remainder = -15 % 2 // -1
(2 * multiplier) + remainder // -15
While the sign of the left operand affects the result of the expression, Swift ignores the sign of the right operand as you can see in the example below.
-15 % 2 // -7
-15 % -2 // -7