Swift中的负随机数

Tar*_*oel 3 swift

我正在开发一个快速的iPhone应用程序,并且有一个要求我总是要生成负的随机数.

我知道生成随机数的方法,但似乎并没有想出一种产生负数的方法.

Dha*_*ngh 12

请尝试使用这个

let lowerValue = -100
let upperValue = 0
let result = Int(arc4random_uniform(UInt32(upperValue - lowerValue + 1))) +   lowerValue

print(result)

Output
Run Code Online (Sandbox Code Playgroud)

-81


Dav*_*nek 5

这是你的功能,我相信:

extension Int {

/// Generates a random `Int` within `0...100`
public static func random() -> Int {
    return random(0...100)
}

/// Generates a random `Int` inside of the closed interval.
public static func random(interval: ClosedInterval<Int>) -> Int {
    return interval.start + Int(arc4random_uniform(UInt32(interval.end - interval.start + 1)))
}

}
Run Code Online (Sandbox Code Playgroud)

用法示例:

Int.random(-10...0)
Run Code Online (Sandbox Code Playgroud)

它取自RandomKit库 - 它看起来非常有用于各种目的.