1

I'm trying to seed a random number generator in Swift using srand(time(NULL)), but I get this compiler error:

Use of unresolved identifier 'NULL'

Is there another way I should be using srand()?

2 Answers 2

9

Swift uses nil for a NULL-pointer, and the return value of time() has to be cast to an UInt32:

srand(UInt32(time(nil))) 

But consider to use arc4random() or its variants instead. From http://nshipster.com/random/:

  • arc4random does not require an initial seed (with srand or srandom), making it that much easier to use.
  • arc4random has a range up to 0x100000000 (4294967296), whereas rand and random top out at RAND_MAX = 0x7fffffff (2147483647).
  • rand has often been implemented in a way that regularly cycles low bits, making it more predictable.

For example,

let x = arc4random_uniform(10) 

generates a random number in the range 0 ... 9.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Martin R. You're right arc4random() is probably a better choice. But I'm glad you cleared up srand() for me.
0

For some compilers this NULL==0 is not true. We are using NULL for pointers. Try this:

srand(time(0)); 

2 Comments

I've tried using srand(time(0)) and get a different error:
The error is 'time_t' is not convertible to 'UInt32'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.