8

My app uses random numbers. I would like to seed the random number generator so that it won't be the same every time. How might I go about doing this?

EDIT:

What parameter do I give srand() to seed the random generator with the current time?

quemeful
  • 9,542
  • 4
  • 60
  • 69
  • Are you asking how to generate a random number in swift? – JSA986 Sep 17 '14 at 16:25
  • no, just asking how to seed the rand() generator – quemeful Sep 17 '14 at 16:30
  • http://stackoverflow.com/questions/24007129/how-does-one-generate-a-random-number-in-apples-swift-language – JSA986 Sep 17 '14 at 16:32
  • possible duplicate of [Using srand(time(NULL)) in swift gives compiler error](http://stackoverflow.com/questions/25610857/using-srandtimenull-in-swift-gives-compiler-error) – Martin R Sep 17 '14 at 16:55
  • 3
    The recommended way of generating random numbers is arc4random_uniform(), which doesn't need to be seeded. – Atomix Sep 17 '14 at 17:13

1 Answers1

8

This works:

let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")
Alberto Barrera
  • 329
  • 1
  • 4
  • is there a way to seed with text and get number as result? – obey Jul 19 '16 at 14:31
  • There are lots. One way would be to get the string's unicodeScalars value, iterate over each item in the collection reading its `value` attribute, and perform some kind of mathematical operation to combine them all into one number. You could just add them all together, but that would mean that anagrams of the same string would have the same seed value - play around with it and I'm sure you can come up with a reasonable solution. – Ash Aug 13 '16 at 19:01
  • 1
    Will that value (NSDate().timeIntervalSinceReferenceDate) ever get too big to fit into a UInt32? – J.Doe Sep 05 '16 at 22:46
  • Notice that srand can't be used in Swift3 anymore. You can use srand48 instead. – endavid Dec 03 '16 at 22:58
  • `srandom()` and `random()` seem to be preferable. – Raphael Apr 04 '17 at 08:04
  • this is no longer valid in Swift 5 – brduca Jan 26 '22 at 11:34