Updated for Xcode 15
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)
BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.