I'm trying to generate seeded random numbers with Swift 4.2+, with the Int.random()
function, however there is no given implementation that allows for the random number generator to be seeded. As far as I can tell, the only way to do this is to create a new random number generator that conforms to the RandomNumberGenerator
protocol. Does anyone have a recommendation for a better way to do it, or an implementation of a RandomNumberGenerator conforming class that has the functionality of being seeded, and how to implement it?
Also, I have seen two functions srand
and drand
mentioned a couple times while I was looking for a solution to this, but judging by how rarely it was mentioned, I'm not sure if using it is bad convention, and I also can't find any documentation on them.
I'm looking for the simplest solution, not necessarily the most secure or fastest performance one (e.g. using an external library would not be ideal).
Update: By "seeded", I mean that I was to pass in a seed to the random number generator so that if I pass in the same seed to two different devices or at two different times, the generator will produce the same numbers. The purpose is that I'm randomly generating data for an app, and rather than save all that data to a database, I want to save the seed and regenerate the data with that seed every time the user loads the app.
Here's alternative to the answer from RPatel99 that accounts GKRandom values range.
So I used Martin R's suggestion to use
GamePlayKit
'sGKMersenneTwisterRandomSource
to make a class that conformed to the RandomNumberGenerator protocol, which I was able to use an instance of in functions likeInt.random()
:Usage:
This gave me the flexibility and easy implementation that I needed by combining the seeding functionality of
GKMersenneTwisterRandomSource
and the simplicity of the standard library's random functions (like.randomElement()
for arrays and.random()
for Int, Bool, Double, etc.)Ref:https://developer.apple.com/documentation/swift/systemrandomnumbergenerator