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?
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.
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.
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.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With