3 回答
TA贡献1848条经验 获得超10个赞
我做了一个Int类型的扩展。在操场上测试它,希望这是有用的。它还接受负范围:
extension Int
{
static func random(range: Range<Int> ) -> Int
{
var offset = 0
if range.startIndex < 0 // allow negative ranges
{
offset = abs(range.startIndex)
}
let mini = UInt32(range.startIndex + offset)
let maxi = UInt32(range.endIndex + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
用得像
var aRandomInt = Int.random(-500...100) // returns a random number within the given range.
或者将它定义为Range扩展名,如下所示:
extension Range
{
var randomInt: Int
{
get
{
var offset = 0
if (startIndex as Int) < 0 // allow negative ranges
{
offset = abs(startIndex as Int)
}
let mini = UInt32(startIndex as Int + offset)
let maxi = UInt32(endIndex as Int + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
}
// usage example: get an Int within the given Range:
let nr = (-1000 ... 1100).randomInt
- 3 回答
- 0 关注
- 849 浏览
添加回答
举报