Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
Why does Swift have a dedicated division remainder operator? - a free tutorial

# Why does Swift have a dedicated division remainder operator?

Paul Hudson    @twostraws

Swift has an operator allows us to calculate the remainder after a division. This is sometimes called modulo, but if you wanted to be really specific it isn’t quite the same thing.

First, let’s look at why it’s useful. If I said to you that there were 465 days until a special event, how would you show that value to a user in a more useful way?

You might start with code like this:

``````let weeks = 465 / 7
print("There are \(weeks) weeks until the event.")``````

That will print that there are 66 weeks until the event, but that isn’t true. When faced with two integers like this, Swift will divide the two and round towards zero to make a whole number. 465 divided by 7 doesn’t equal exactly 66, so folks might miss your event entirely!

Your second attempt might tell Swift to use a `Double` rather than an `Int`, so we get a more accurate answer:

``````let weeks: Double = 465 / 7
print("There are \(weeks) weeks until the event.")``````

But now we get something that’s Technically Correct™ but not actually that useful: there are 66.42857142857143 weeks until the event.

This is where the remainder operator comes in:

``````let weeks = 465 / 7
let days = 465 % 7
print("There are \(weeks) weeks and \(days) days until the event.")``````

So, `weeks` divides 465 by 7 and rounds towards 0, giving 66 weeks, then `days` uses the remainder operator to calculate how much was left over.

The remainder operator is really useful and comes up a lot. For example, many tables of data use “zebra striping” – they alternate the colors of rows to make them easier to read.

Tip: If your goal is to ask “does this number divide equally into some other number?” then Swift has an easier approach:

``````let number = 465
let isMultiple = number.isMultiple(of: 7)``````

SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.

Sponsor Hacking with Swift and reach the world's largest Swift community!