返回一个范围内的整数数组

时间:2017-02-28 19:44:41

标签: arrays swift random swift3

我是Swift的新手,想创建一个返回随机整数数组的函数,所有函数都在指定的范围内。这就是我想出来的,但对我来说并不觉得“非常”。精通Swift的人会采用不同的方法吗?

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)

1 个答案:

答案 0 :(得分:3)

函数randomNumber() 昂贵效率不高,因为minmax在每次调用中被提取(也就是在循环的每次迭代中)

这可能有点 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)