Back in the Swift 4 days, I implemented a RandomNumberGenerator
for the purpose of testing, which is to say, it always returns the same sequence of UInt64's,
so that I can validate code that accepts a RandomNumberGenerator.
However, as of "circa" Swift 5, this test is reliably failing, because even though it returns a different number in the next function, it fails to return any element except the first one from arrays (sequences, etc.).
Sample code is here:
class MockRandomNumberGenerator: RandomNumberGenerator {
var current: UInt64 = 0
func next() -> UInt64 {
defer { current += 1 }
return current
}
}
var mockRandomNumberGenerator = MockRandomNumberGenerator()
let testArray = 0..<10
for _ in 0..<testArray.count {
print("testArray.randomElement : \(testArray.randomElement(using: &mockRandomNumberGenerator)!)")
print("testArray[Int.random(...)]: \(testArray[Int.random(in: 0..<testArray.count, using: &mockRandomNumberGenerator)])")
}
The output of this is always 0, for every iteration. I expected the sequence to be returned in order, from 0 to 9. So, it fails in the same way for both array randomElement()
and range random(in:).
Prior to Swift 5, this same implementation returned the sequence in order.
What do I need to do in the random number generator implementation to get it to work with arrays (and ranges) correctly?