2015-10-15 98 views
4

我得到3個不同的功能,我想隨機調用其中之一。快速通話隨機功能

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

使用此代碼我調用所有函數,並且順序始終相同。我能做些什麼來調用其中之一?

回答

5

原因三個函數調用(並以相同的順序)是因爲你是導致當你把它們放在數組中他們被調用。

此:因爲要調用它們(通過添加「()」)的陣列中的每個函數的

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

商店返回值。

在這一點上 randomFunc

所以包含返回值,而不是功能關閉

,而不是僅僅存儲與函數本身:

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

現在,如果你想調用所選擇的方法不返回其關閉,但它援引它:

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

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

謝謝,現在它的作品完美。 –

-1

我希望它應該工作

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