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?
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?
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)))
This seems to be available for me, currently on Swift 3.1, so possible it was added back.
My guess is that it's somewhere in Foundation and needs an explicit import Foundation
Update
This is for Int types only. It seems that for doubles, truncating remainder is required.
As per new Guideline Swift 5, it's changed
value.truncatingRemainder(dividingBy: 2)
You can use this code to find the modulus of 2 numbers. label.text is to display the result in a label that I have already designed
let result = Int(num1) % Int(num2)
label.text = String(Int(result))
Use https://developer.apple.com/documentation/swift/double/2884269-remainder
If you use truncatingRemainder (as mentioned in the other comments) then it is going to floor the value first, which means 3.14 is going to become 3.