Ios 从同一作用域调用块/闭包

Ios 从同一作用域调用块/闭包,ios,swift,timer,closures,Ios,Swift,Timer,Closures,我正在创建一个应用程序,它的屏幕可以在黑白之间快速切换。为此,我使用计时器 我的问题归结为不能从计时器声明中的同一作用域changeBackgroundColor调用函数 let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: changeBackgroundColor) //Error: 'Cannot convert value of type '(ViewController) ->

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

我的问题归结为不能从计时器声明中的同一作用域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)
}

我以为我理解闭包,但这里的作用域似乎有问题

使用计时器块版本的全部目的是避免创建单独的函数

你应该这样写:

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

在有自引用之前,类的属性被赋予它们的初始值。当self可用时,您只需要在另一个时间初始化它。但是在my ToucheSBegind中启动计时器使其无法从touchesEnded中失效。将计时器设置为属性而不是局部变量。但这不会在ViewController加载时立即启动它吗?不。您仍然可以在需要的地方创建计时器。您只需更改变量的范围,以便可以从其他方法访问它。