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

后端 未结 3 2126
离开以前
离开以前 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:30

    Edited to remove modulo bias per the suggestion in comments. (thanks!)

    I think a neat way of doing this may be to use Swift's Range to define the bounds because then you can specify 1..100 or 1...100 (including or excluding the upper bound). The best I have come up with so far is:

    import Foundation // needed for rand()
    
    func randInRange(range: Range) -> Int {
        // arc4random_uniform(_: UInt32) returns UInt32, so it needs explicit type conversion to Int
        // note that the random number is unsigned so we don't have to worry that the modulo
        // operation can have a negative output
        return  Int(arc4random_uniform(UInt32(range.endIndex - range.startIndex))) + range.startIndex
    }
    
    // generate 10 random numbers between -1000 and 999
    for _ in 0...100 {
        randInRange(-1000...1000)
    }
    

    I tried using an extension on Range but you cannot seem to extend Range< T where T: Int > specifically. It would be even better if you could get a syntax like (1..100).rand().

提交回复
热议问题