Joe Man Joe Man -4 years ago 127
Swift Question

Return an array of Integers within a range

I am very new to Swift and would like to create a function that returns an array of random integers, all within a specified range. This is what I've come up with but it doesn't feel very "Swifty" to me. Would someone proficient with Swift take a different approach?

func randomNumber(range: ClosedRange<Int>) -> Int {
let min = range.lowerBound
let max = range.upperBound
return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}

func randomNumbers(range: ClosedRange<Int>, count: Int) -> [Int] {
var array = [Int]()

for _ in 0..<count {
let n = randomNumber(range: range)
array.append(n)
}

return array
}

let nums = randomNumbers(range: 10...20, count: 5)

Answer Source

The function randomNumber() is expensive not efficient because min and max are extracted in each call (aka in each iteration of the loop)

This might be a bit swiftier

func randomNumbers(range: ClosedRange<Int>, count: Int) -> [Int] {
    let min = range.lowerBound
    let randomMax = UInt32(1 + range.upperBound - min)
    return (0..<count).map {_ in return Int(arc4random_uniform(randomMax)) + min }
}

let nums = randomNumbers(range: 10...20, count: 5)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download