繁体   English   中英

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

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

例如,开始重复计时器的 swift function:

  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 function 在计时器关闭开始运行之前很久就返回了,那么 runCount 变量如何仍在 scope 中?

这就是为什么它们被称为闭包。

闭包可以从定义它们的上下文中捕获和存储对任何常量和变量的引用。 这被称为关闭这些常量和变量。 Swift 为您处理所有的 memory 管理捕获。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM