Mat*_*man 5 function ios swift
我有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]
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,我调用所有函数,顺序始终相同.我可以做些什么来打电话给其中一个?
调用这三个函数(并以相同的顺序)的原因是,当您将它们放入数组时,它们会被调用.
这个:
let randomFunc = [self.firstFunction(), self.secondFunction(), self.thirdFunction()]
Run Code Online (Sandbox Code Playgroud)
存储数组中每个函数的返回值,因为您正在调用它们(通过添加' ()').
所以此时randomFunc包含返回值而不是函数闭包
而只是存储函数本身:
[self.firstFunction, self.secondFunction, self.thirdFunction]
Run Code Online (Sandbox Code Playgroud)
现在,如果要调用selected方法,则不返回其闭包但调用它:
//return randomFunc[randomResult] // This will return the function closure
randomFunc[randomResult]() // This will execute the selected function
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
450 次 |
| 最近记录: |