Hack Saw
Hack Saw

Reputation: 2781

Cannot convert value of type 'Range<Int>' to expected argument type 'Range<_>'

Using Swift 4.2, I get the title as an error in this function:

func jitter(range: Int) -> Int {
    return Int.random(in: 0..<range, using: SystemRandomNumberGenerator())
}

Questions:

  1. What precisely does Range<_> mean?
  2. Is there a better way to get this? I simply want a small random number inside an animation loop.

Upvotes: 0

Views: 599

Answers (1)

Ole Begemann
Ole Begemann

Reputation: 135588

The Swift compiler is giving you a bad error message. The problem is that the second argument to Int.random(in:using:) must be passed inout (i.e. with a & prefix). This works:

func jitter(range: Int) -> Int {
    var rng = SystemRandomNumberGenerator()
    return Int.random(in: 0..<range, using: &rng)
}

Even easier, omit the using: parameter altogether (SystemRandomNumberGenerator is the default RNG anyway):

func jitter(range: Int) -> Int {
    return Int.random(in: 0..<range)
}

Upvotes: 1

Related Questions