Search code examples
iosswiftarc4random

Impose limitations on arc4random()?


In Swift, I am using arc4random to generate a number between 0 and 568.

I need it impose limitations on this however. For example, the number can't be between 10 and 40. How are these "limitations" added?


Solution

  • Just keep trying until the condition is met:

    func funnyRandom() -> UInt32 {
        var ran: UInt32 = 0
        do {
            ran = arc4random_uniform(568)
        } while (ran > 10 && ran < 40)
        return ran;
    }
    

    In Objective-C, it is the same method as in Swift:

    - (int)funnyRandom {
        int ran;
        do {
            ran = arc4random_uniform(568);
        } while (ran > 10 && ran < 40);
        return ran;
    }