bmaliel bmaliel - 2 months ago 15
Swift Question

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

I'm pretty new to Swift and programming logic in general so bare with me

How can you generate a random number between 0 and 9 in Swift without repeating the last generated number? As in the same number won't come up twice in a row.

Answer

Store the previous generated number in a variable and compare the generated number to the previous number. If they match generate a new random number. Repeat the generation of new numbers until they don't match.

var previousNumber: UInt32? // used in randomNumber() 

func randomNumber() -> UInt32 {
    var randomNumber = arc4random_uniform(10)
    while previousNumber == randomNumber {
        randomNumber = arc4random_uniform(10)
    }
    previousNumber = randomNumber
    return randomNumber
}
Comments