Mat Koffman
Mat Koffman

Reputation: 607

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?

Upvotes: 5

Views: 913

Answers (3)

yefimovv
yefimovv

Reputation: 7

if Int(ball.position.y) > maxIndexY! {

let randomNumber = Int.random(in: 0...2)

if randomNumber == 0 {
    firstFunction()
} else if randomNumber == 1 {
    secondFunction()
} else if randomNumber == 2 {
    thirdFunction()
}
}

Upvotes: 0

giorashc
giorashc

Reputation: 13713

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

Upvotes: 7

Arsen
Arsen

Reputation: 10951

I expect it should work

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

Upvotes: -1

Related Questions