mardi 28 février 2017

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)




Aucun commentaire:

Enregistrer un commentaire