2

Swift mod operator (%)

 1 year ago
source link: https://sarunw.com/posts/swift-mod/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Swift mod operator (%)

08 Dec 2022 ⋅ 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 (%).

There is a difference between the remainder operator and the modulo operator. The behavior is different when dealing with negative numbers.

If you want to find a remainder between two positive numbers, these two shouldn't make a difference.

But if you really want a Modulo operator, Swift Remainder Operator isn't what you are looking for.

You can easily support sarunw.com by checking out this sponsor.

Reliable mobile testing for iOS apps:

Sponsor sarunw.com and reach thousands of iOS developers.

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK