我意识到Swift书籍提供了一个随机数生成器的实现。复制和粘贴这个实现是最佳实践吗?或者有没有这样的库,我们现在就可以使用?


当前回答

斯威夫特4.2

Swift 4.2在标准库中包含了一个原生的、功能相当全的随机数API。(Swift Evolution提案SE-0202)

let intBetween0to9 = Int.random(in: 0...9) 
let doubleBetween0to1 = Double.random(in: 0...1)

所有的数字类型都有静态随机数(in:),它接受范围并返回给定范围内的随机数

其他回答

你可以像在C中那样做:

let randomNumber = arc4random()

推断randomNumber类型为UInt32(32位无符号整数)

Swift 4 + 2。

Xcode 10附带的Swift 4.2为许多数据类型引入了新的易于使用的随机函数。

只需在数值类型上调用random()方法。

let randomInt = Int.random(in: 0..<6)
let randomDouble = Double.random(in: 2.71828...3.14159)
let randomBool = Bool.random()

在某些版本的Xcode中没有arc4Random_uniform()(在7.1中运行,但对我来说不自动完成)。你可以这样做。

从0-5中生成一个随机数。 第一个

import GameplayKit

Then

let diceRoll = GKRandomSource.sharedRandom().nextIntWithUpperBound(6)

@jstn的回答很好,但有点啰嗦。Swift被称为面向协议的语言,因此我们可以通过为协议扩展添加默认实现,而不必为整数族中的每个类实现样板代码来实现相同的结果。

public extension ExpressibleByIntegerLiteral {
    public static func arc4random() -> Self {
        var r: Self = 0
        arc4random_buf(&r, MemoryLayout<Self>.size)
        return r
    }
}

现在我们可以做:

let i = Int.arc4random()
let j = UInt32.arc4random()

其他的整数类都是可以的。

我已经能够使用rand()来获得一个随机的CInt。你可以使用这样的方法使它成为Int型:

let myVar: Int = Int(rand())

你可以使用你最喜欢的C随机函数,并在需要时将值转换为Int。