How to generate a random number in Swift without repeating the previous random number?

my solution, i think its easy to understand

var nums = [0,1,2,3,4,5,6,7,8,9]

while nums.count > 0 {

    // random key from array
    let arrayKey = Int(arc4random_uniform(UInt32(nums.count)))

    // your random number
    let randNum = nums[arrayKey] 

    // make sure the number isnt repeated
    nums.swapAt(arrayKey, nums.count-1)
    nums.removeLast()
}

Leave a Comment