你如何在swift中生成一个随机数?

slo*_*ker 5 random swift

TL:博士; 如何生成随机数,因为书中的方法每次都会选择相同的数字.

根据Apple发布的书,这似乎是Swift生成随机数的方式.

protocol RandomNumberGenerator {
    func random() -> Double
}
class LinearCongruentialGenerator: RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0
    func random() -> Double {
        lastRandom = ((lastRandom * a + c) % m)
        return lastRandom / m
    }
}
let generator = LinearCongruentialGenerator()

for _ in 1..10 {
    // Generate "random" number from 1-10
    println(Int(generator.random() * 10)+1)
}
Run Code Online (Sandbox Code Playgroud)

问题是,在我放在底部的for循环中,输出如下所示:

4
8
7
8
6
2
6
4
1
Run Code Online (Sandbox Code Playgroud)

无论我运行多少次,每次输出都是相同的.

Anu*_*oob 5

您创建的随机数生成器不是真正随机的,它是psueodorandom.

使用伪随机数随机数生成器,序列取决于种子.更改种子,您更改序列.

一种常见的用法是将种子设置为当前时间,这通常使其足够随机.

您也可以使用标准库:arc4random().别忘了import Foundation.