随机数在OC中真心简单啊 srand(time(null)),可是这样的代码到了 Swift中就行不通了
首先:swift没有null,time(nil)出来的又是 int,但 srand 的传入参数 又是Uint32.。。所以好让人纠结
不过网上还是有高手,他们说,你可以这样:srand(UInt32(time(nil))),看上去和原来的OC几乎一样,当然 他还提出了
XML/HTML代码
- 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.
可是还有人说:
XML/HTML代码
- let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
- srand(time)
- print("Random number: \(rand()%10)")
得,还是能用就成