Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the modulus operator (%) in swift 3?

Tags:

swift3

modulus

I have this line:

randomIndex = Int(drand48() % Double(alphabetColors.count)) 

And Xcode 8 (Swift 3) tells me:

'%' is unavailable: Use truncatingRemainder instead 

Is there no operator anymore? How should I convert my code?

like image 693
Kalzem Avatar asked Oct 27 '16 20:10

Kalzem


People also ask

What the modulus operator (%) does?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division.

What is a modulus operator in Swift?

Swift has a dedicated remainder operator in the form of % , and it's used to return the remainder after dividing one number wholly into another. For example, 14 % 3 is 2, because you can fit four 3s into 14, and afterwards you have the remainder 2.

How do you write a modulus operator?

Enter the Modulo The modulo operation (abbreviated “mod”, or “%” in many programming languages) is the remainder when dividing. For example, “5 mod 3 = 2” which means 2 is the remainder when you divide 5 by 3.

What does || mean in Swift?

|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.


1 Answers

You can simply follow the diagnostic message:

let randomIndex = Int(drand48().truncatingRemainder(dividingBy: Double(alphabetColors.count))) 

Or using arc4random_uniform(_:) would be a better alternative.

let randomIndex = Int(arc4random_uniform(UInt32(alphabetColors.count))) 
like image 139
OOPer Avatar answered Nov 12 '22 16:11

OOPer