简体   繁体   English

在 Swift 中生成随机数

[英]Generating a random number in Swift

I read in https://www.hackingwithswift.com/read/35/2/generating-random-numbers-in-ios-8-and-earlier that the best way to generate a random number is to use我在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)]

but it seems odd that I have to cast twice to be able to get a random number, what should I do to avoid casting?但是我必须投射两次才能获得随机数似乎很奇怪,我应该怎么做才能避免投射?

It really depends on how much casting you want to avoid.这真的取决于你想避免多少铸造。 You could simply wrap it in a function:你可以简单地将它包装在一个函数中:

func random(max maxNumber: Int) -> Int {
    return Int(arc4random_uniform(UInt32(maxNumber)))
}

So then you only have to do the ugly casting once.那么你只需要做一次丑陋的铸造。 Everywhere you want a random number with a maximum number:你想要一个具有最大数量的随机数的地方:

let r = random(max: _names.count)
let name: String = _names[r]

As a side note, since this is Swift, your properties don't need _ in front of them.附带说明一下,由于这是 Swift,因此您的属性不需要_在它们前面。

I really like using this extension我真的很喜欢使用这个扩展

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
    }
}

Now you can generate a random Int indicating the range现在您可以生成一个随机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

you can use gameplaykit你可以使用gameplaykit

let random = GKRandomDistribution(lowestValue: 0, highestValue: 100)
let r = random.nextInt()

Modified answer from Luca written as extension in Swift 4 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
    }
}

Examples:例子:

(0...10).random
(0..<10).random

Swift 4.2 and above Swift 4.2 及以上

You can initial a random element:您可以初始化一个随机元素:

let randomInt = Int.random(in: 0...1)
let randomDouble = Double.random(in: 0...1)

Also You can take a random element from a collection like你也可以从一个集合中随机抽取一个元素

let randomInt = (0...9).randomElement()

Also there is another handy method that you can use on array for shuffling that you may need:还有另一种方便的方法,您可以在数组上使用您可能需要的洗牌方法:

let shuffled = [1, 2, 3, 4].shuffled()

或者你可以使用

 let name : String = _names[ Int(arc4random()) % _names.count ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM