Search code examples
swift3modulus

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


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?


Solution

  • 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)))