Search code examples
swiftif-statementibactionarc4random

Is there a way to shorten if statements with arc4random_uniform( ) inside them?


I am having some trouble with some if-statements. I am trying to figure out how to shorten if-statements with arc4random_uniform inside them. Here is my code:

func firstCustomNumberRange(sender : AnyObject){

    if (firstCustomNumberRangeLabel == 1 )
    {
        var randomNumber = 1
    }


    if (firstCustomNumberRangeLabel == 2 )
    {
        var randomNumber = arc4random_uniform( 2) + 1
    }


    if (firstCustomNumberRangeLabel == 3 )
    {
        var randomNumber = arc4random_uniform( 3) + 1
    }


    if (firstCustomNumberRangeLabel == 4 )
    {
        var randomNumber = arc4random_uniform( 4) + 1
    }
     ...}

(I repeated the pattern up to 20). This was a very time consuming process and it took me about 30 minutes just to write these simple if-statements.

Is it possible to shorten if statements with custom arc4random_uniform( ) inside them.

Thanks in advance.


Solution

  • Just pass the value of firstCustomNumberRangeLabel to arc4random_uniform() directly:

    func firstCustomNumberRange(sender : AnyObject){
        if let numberRange = NSNumberFormatter().numberFromString(firstCustomNumberRangeLabel.text!) {
            let randomNumber = arc4random_uniform(UInt32(numberRange.unsignedIntegerValue)) + 1
        }
    }