我在https://www.hackingwithswift.com/read/35/2/generating-random-numbers-in-ios-8-and-earlier中读到,生成随机数的最佳方法是使用
let r = arc4random_uniform(UInt32(_names.count))
let name : String = _names[Int(r)]
但似乎很奇怪我必须投两次以获得一个随机数,我应该怎么做以避免投射?
答案 0 :(得分:7)
这实际上取决于你想要避免多少铸造。你可以简单地将它包装在一个函数中:
func random(max maxNumber: Int) -> Int {
return Int(arc4random_uniform(UInt32(maxNumber)))
}
那么你只需做一次丑陋的施法。无处不在你需要一个最大数字的随机数:
let r = random(max: _names.count)
let name: String = _names[r]
作为旁注,由于这是Swift,因此您的属性不需要_
。
答案 1 :(得分:3)
我真的很喜欢使用此扩展程序
extension Int {
init(random range: Range<Int>) {
let offset: Int
if range.startIndex < 0 {
offset = abs(range.startIndex)
} else {
offset = 0
}
let min = UInt32(range.startIndex + offset)
let max = UInt32(range.endIndex + offset)
self = Int(min + arc4random_uniform(max - min)) - offset
}
}
现在,您可以生成指示范围的随机Int
let a = Int(random: 1...10) // 3
let b = Int(random: 0..<10) // 6
let c = Int(random: 0...100) // 31
let d = Int(random: -10...3) // -4
答案 2 :(得分:1)
你可以使用gameplaykit
let random = GKRandomDistribution(lowestValue: 0, highestValue: 100)
let r = random.nextInt()
答案 3 :(得分:1)
来自Luca的修改后的答案,写在Swift 4中作为扩展名
/// Returns random number within given range, upper bound included, eg. -1...0 = [-1, 0, 1]
extension CountableClosedRange where Bound == Int
{
var random: Int
{
let range = self
let offset: Int = range.lowerBound < 0 ? abs(range.lowerBound) : 0
let min = UInt32(range.lowerBound + offset)
let max = UInt32(range.upperBound + offset)
let randomNumber = Int(min + arc4random_uniform(max - min + 1)) - offset
return randomNumber
}
}
/// Returns random number within given range, upper bound not included, eg. -1...0 = [-1, 0]
extension CountableRange where Bound == Int
{
var random: Int
{
let range = self
let offset: Int = range.lowerBound < 0 ? abs(range.lowerBound) : 0
let min = UInt32(range.lowerBound + offset)
let max = UInt32(range.upperBound + offset)
let randomNumber = Int(min + arc4random_uniform(max - min)) - offset
return randomNumber
}
}
示例:
(0...10).random
(0..<10).random
答案 4 :(得分:1)
您可以初始化随机元素:
let randomInt = Int.random(in: 0...1)
let randomDouble = Double.random(in: 0...1)
您还可以从类似的集合中获取随机元素
let randomInt = (0...9).randomElement()
另外,您还可以在数组上使用另一种便捷的方法来洗牌,这可能是您需要的:
let shuffled = [1, 2, 3, 4].shuffled()
答案 5 :(得分:0)
或者你可以使用
let name : String = _names[ Int(arc4random()) % _names.count ]