NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

Why does Swift have a dedicated division remainder operator?

Paul Hudson    @twostraws   

Updated for Xcode 13.3

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)
Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.