Swift mod operator (%)

⋅ 1 min read ⋅ Swift String

Table of Contents

Mod or Modulo operator (%) usually refers to an operator that returns the remainder of the division.

In Swift, this operator is called Remainder Operator (%).

Remainder Formula

The Remainder operator has the following formula.

Dividend = Divisor x Quotient + Remainder

Therefore,

Remainder = Dividend – (Divisor x Quotient)

Dividend is a value that is to be divided by another value.
Divisor is the number which divides the dividend.
Quotient is the result of the division process.
Remainder is what remains after the division.

It is easier to understand with an example.

Example: 9 % 4.

let quotient = 9 / 4
// 2

let remainder = 9 % 4
// 1

Remainder Operator with negative numbers

The remainder operator can be used with negative numbers, but the calculation isn't straightforward.

Here is the rule:

  • Perform the operation as if both operands were positive.
  • If the left operand (dividend) is negative, then make the result negative.
  • If the left operand is positive, then make the result positive.
  • Ignore the sign of the right operand (divisor) in all cases.

For example:

9 % 4 // 1
9 % -4 // 1

-9 % 4 // -1
-9 % -4 // -1

Read more article about Swift, String, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
What is Button Role in SwiftUI

Learn what it is and how it affects a button.

Next
How to Reorder List rows in SwiftUI List

Learn how to enable/disable the reorder ability in SwiftUI List.

← Home