nsko
nsko

Reputation: 310

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

For example, a swift function which starts repeating timer:

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

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

I'm confused how it's possible to use runCount variable inside timer closure? If runTimer function returns long before the timer closure starts running, how is the runCount variable still in scope?

Upvotes: 1

Views: 659

Answers (1)

Shadowrun
Shadowrun

Reputation: 3857

This is why they're called closures.

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

Upvotes: 2

Related Questions