Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift call random function

I got 3 different functions and I want to call one of these randomly.

    if Int(ball.position.y) > maxIndexY! {
        let randomFunc = [self.firstFunction(), self.secondFunction(), self.thirdFunction()]
        let randomResult = Int(arc4random_uniform(UInt32(randomFunc.count)))
        return randomFunc[randomResult]
    }

With this code I call all functions, and the order is always the same. What can I do to just call one of these?

like image 670
Mat Koffman Avatar asked Oct 15 '15 11:10

Mat Koffman


People also ask

What is arc4random Swift?

The arc4random() function generates numbers between 0 and 4,294,967,295, giving a range of 2 to the power of 32 - 1, i.e., a lot. But if you wanted to generate a random number within a specific range there's a better alternative.


1 Answers

The reason the three functions are called (and in the same order) is since you are causing them to be called when you put them in the array.

This:

let randomFunc = [self.firstFunction(), self.secondFunction(), self.thirdFunction()]

Stores the return value of each function in the array since you are invoking them (by adding the '()').

So at this point randomFunc contains the return values rather than the function closures

Instead just store the functions themselves with:

[self.firstFunction, self.secondFunction, self.thirdFunction]

Now if you want to call the selected method do not return its closure but invoke it:

 //return randomFunc[randomResult] // This will return the function closure 

 randomFunc[randomResult]() // This will execute the selected function
like image 64
giorashc Avatar answered Oct 09 '22 16:10

giorashc