在Swift中,如果在闭包中使用,局部变量的作用域是什么?

In Swift, what is the scope of local variable if it is used inside a closure?

例如,启动重复计时器的 swift 函数:

  func runTimer() {
        var runCount = 0
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            print("Timer fired!")
            runCount += 1              

            if runCount == 3 {
                timer.invalidate()
            }
        }
   }

我很困惑如何在定时器闭包中使用 runCount 变量?如果 runTimer 函数 returns 在计时器关闭开始 运行 之前很久,runCount 变量如何仍在范围内?

这就是它们被称为闭包的原因。

Closures can capture and store references to any constants and variables from the context in which they’re defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

https://docs.swift.org/swift-book/LanguageGuide/Closures.html#ID103