从同一范围调用块/闭包

时间:2022-07-19 13:33:44

I am creating an app that has the screen switch rapidly between black and white. For this I am using a Timer,

我正在创建一个在黑白之间快速切换屏幕的应用程序。为此,我使用的是计时器,

My problem boils down to not being able to call a function from the same scope (changeBackgroundColor) in timer's declaration.

我的问题归结为无法在timer的声明中调用同一范围(changeBackgroundColor)中的函数。

let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: changeBackgroundColor) 
//Error: 'Cannot convert value of type '(ViewController) -> (Timer) -> Void' to expected argument type '(Timer) -> Void'

func changeBackgroundColor(timer: Timer) -> Void {
    //change the color of the screen (not the issue here)
}

I thought I had understood closures but there seems to be a problem with the scopes here.

我以为我已经理解了闭包,但这里的示波器似乎存在问题。

1 个解决方案

#1


1  

The whole point of using the "block" version of a timer is to avoid having to create a separate function.

使用计时器的“块”版本的全部意义在于避免必须创建单独的功能。

You should write it as follows:

你应该写如下:

let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
    // change the color of the screen
}

#1


1  

The whole point of using the "block" version of a timer is to avoid having to create a separate function.

使用计时器的“块”版本的全部意义在于避免必须创建单独的功能。

You should write it as follows:

你应该写如下:

let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
    // change the color of the screen
}