Zablah Zablah - 5 months ago 33
Swift Question

How to exclude specific Integers from arc4random

I want to get a random number with

arc4random_uniform()
but excluding the numbers from an array like this

var numbersArray = [8,15,10,3,7]
var randomNumber = arc4random_uniform(20)


If the
arc4random_uniform()
gives me any number from the
numbersArray
I want it to get a new number that is not from the
numbersArray


I tried this

func getRandomGroup() -> Int {
for numbers in numbersArray {
if numbers == randomNumber {
var randomNumber = arc4random_uniform(20)
}
}
return randomNumber
}


But it did not seemed to work

Answer

Swift 2.0

var numbersArray = [8,15,10,3,7]
var randomNumber : Int
repeat {
    randomNumber = Int(arc4random_uniform(20))
} while numbersArray.contains(randomNumber) 
print(randomNumber)

In Swift 1.x it is do while

Comments