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?

5
  • Are you asking how to generate a random number in swift? Commented Sep 17, 2014 at 16:25
  • no, just asking how to seed the rand() generator Commented Sep 17, 2014 at 16:30
  • stackoverflow.com/questions/24007129/… Commented Sep 17, 2014 at 16:32
  • possible duplicate of Using srand(time(NULL)) in swift gives compiler error Commented Sep 17, 2014 at 16:55
  • 3
    The recommended way of generating random numbers is arc4random_uniform(), which doesn't need to be seeded. Commented Sep 17, 2014 at 17:13

1 Answer 1

8

This works:

let time = UInt32(NSDate().timeIntervalSinceReferenceDate) srand(time) print("Random number: \(rand()%10)") 
Sign up to request clarification or add additional context in comments.

6 Comments

is there a way to seed with text and get number as result?
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.
Will that value (NSDate().timeIntervalSinceReferenceDate) ever get too big to fit into a UInt32?
Notice that srand can't be used in Swift3 anymore. You can use srand48 instead.
srandom() and random() seem to be preferable.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.