Using srand (time (NULL)) in Swift gives a compiler error

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

Using an Unresolved Identifier "NULL"

Is there any other way to use srand ()?

+1
source share
2 answers

Swift uses nil for a NULL pointer, and the return value of time() must be pressed on UInt32 :

 srand(UInt32(time(nil))) 

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

  • arc4random does not require an initial seed (with srand or srandom ), which makes it much easier to use.
  • arc4random has a range up to 0x100000000 (4294967296), while rand and random end with RAND_MAX = 0x7fffffff (2147483647).
  • rand often implemented in such a way that it regularly processes low bits cyclically, making it more predictable.

For instance,

 let x = arc4random_uniform(10) 

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

+9
source

For some compilers, this NULL==0 not true. We use NULL for pointers. Try the following:

 srand(time(0)); 
0
source

Source: https://habr.com/ru/post/1202790/


All Articles