What is the easiest way to generate random integers within a range in Swift?

后端 未结 3 2127
离开以前
离开以前 2020-12-15 06:09

The method I\'ve devised so far is this:

func randRange (lower : Int , upper : Int) -> Int {
    let difference = upper - lower
    return Int(Float(rand(         


        
3条回答
  •  无人及你
    2020-12-15 06:31

    Here's a somewhat lighter version of it:

    func randRange (lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
    }
    

    This can be simplified even further if you decide this function works with unsigned values only:

    func randRange (lower: UInt32 , upper: UInt32) -> UInt32 {
        return lower + arc4random_uniform(upper - lower + 1)
    }
    

    Or, following Anton's (+1 for you) excellent idea of using a range as parameter:

    func random(range: Range) -> UInt32 {
        return range.startIndex + arc4random_uniform(range.endIndex - range.startIndex + 1)
    }
    

提交回复
热议问题