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()?
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/:
arc4randomdoes not require an initial seed (withsrandorsrandom), making it that much easier to use.arc4randomhas a range up to 0x100000000 (4294967296), whereasrandandrandomtop out at RAND_MAX = 0x7fffffff (2147483647).randhas 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.
For some compilers this NULL==0 is not true. We are using NULL for pointers. Try this:
srand(time(0));