我需要生成一个随机数。
看来该arc4random功能已不复存在arc4random_uniform。
arc4random
arc4random_uniform
我的选择是arc4random_stir(), arc4random_buf(UnsafeMutablePointer<Void>, Int)和 arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32)。
arc4random_stir()
arc4random_buf(UnsafeMutablePointer<Void>, Int)
arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32)
我在函数上找不到任何文档,头文件中也没有注释。
===== Swift 4.2 / Xcode 10 =====
let randomIntFrom0To10 = Int.random(in: 1..<10) let randomFloat = Float.random(in: 0..<1) // if you want to get a random element in an array let greetings = ["hey", "hi", "hello", "hola"] greetings.randomElement()
斯威夫特在引擎盖下arc4random_buf用来完成工作。
arc4random_buf
===== Swift 4.1 / Xcode 9 =====
arc4random()返回 0* 到 4294967295之间 的随机数 *
arc4random()
drand48()返回 0.0* 到 1.0 范围内的随机数 *
drand48()
arc4random_uniform(N)返回 0* 到 N-1 范围内的随机数 *
arc4random_uniform(N)
例子:
arc4random() // => UInt32 = 2739058784 arc4random() // => UInt32 = 2672503239 arc4random() // => UInt32 = 3990537167 arc4random() // => UInt32 = 2516511476 arc4random() // => UInt32 = 3959558840 drand48() // => Double = 0.88642843322303122 drand48() // => Double = 0.015582849408328769 drand48() // => Double = 0.58409022031727176 drand48() // => Double = 0.15936862653180484 drand48() // => Double = 0.38371587480719427 arc4random_uniform(3) // => UInt32 = 0 arc4random_uniform(3) // => UInt32 = 1 arc4random_uniform(3) // => UInt32 = 0 arc4random_uniform(3) // => UInt32 = 1 arc4random_uniform(3) // => UInt32 = 2
*建议在诸如此类的结构上使用 *arc4random_uniform(),arc4random() % upper_bound因为当上限不是2的幂时,它会避免“模偏差”。
arc4random() % upper_bound