Quick call function

I have 3 different functions, and I want to call it by accident.

    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 the functions, and the order is always the same. What can I do to just name one of them?

+4
source share
2 answers

The reason why three functions are called (and in the same order), because you call them when called, when you put them in an array.

It:

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

Stores the return value of each function in an array as you call them (by adding ` ()`).

So, at this point, the randomFuncreturn values ​​are contained, not the function closures

Instead, just save the functions themselves:

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

, , , :

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

 randomFunc[randomResult]() // This will execute the selected function
+5

,

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]()
}
-1

Source: https://habr.com/ru/post/1611771/


All Articles