36

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?

Kalzem
  • 7,320
  • 6
  • 54
  • 79
  • 1
    The % operator is a remainder operation not a modulo operator in Swift. Here is some talk about it: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160523/018679.html – wazy Oct 27 '16 at 20:19
  • I have done this way.. https://stackoverflow.com/a/49769128/5315917 – Dimple Shah Apr 11 '18 at 07:36

6 Answers6

37

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)))
OOPer
  • 47,149
  • 6
  • 107
  • 142
34

enter image description here

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.

Logan
  • 52,262
  • 20
  • 99
  • 128
  • That's odd, I can't find anything about it on https://apple.github.io/swift-evolution/ for Swift 3.1. Isn't there a third party library on your side which can induce this behaviour? – Kalzem Mar 29 '17 at 17:59
  • 2
    Oh you are right, I found a paragraph about it on the official documentation https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html They call it the **remainder** operator – Kalzem Mar 29 '17 at 18:02
14

Cast your variable to Int before mod

example

let result = Int(value) % 3
benmore99
  • 903
  • 9
  • 17
5

As per new Guideline Swift 5, it's changed

value.truncatingRemainder(dividingBy: 2)
kishor soneji
  • 795
  • 1
  • 9
  • 16
1

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))
JESTIN SAJI
  • 53
  • 1
  • 15
0

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.