Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Closures in Swift First Class Functions Capturing Variables

Kristof Kocsis
Kristof Kocsis
15,455 Points

Is this the work of ARC?

Ok so all this is possible because of ARC? The variable localCounter is kept alive because it has at least 1 reference?

The references go like this: counter -> increment -> localCounter

Is this right, or is there another reason and I'm misunderstanding it?


The code from the video:

typealias IntegerFunction = (Int) -> Void

func gameCounter() -> IntegerFunction {

    var localCounter = 0

    func increment(_ i: Int) {
        localCounter += i
        print("Local counter value: \(localCounter)")
    }

    return increment(_:)
}

let counter = gameCounter()
counter(1)
counter(1)

1 Answer

It's possible because of a special feature of closures that uses ARC (Automatic Reference Counting). Since the increment function gets returned from the gameCounter function and assigned to a constant (counter), the compiler knows it has to keep any variables and constants that it uses alive. So the compiler creates a reference to this particular instance of localCounter and stores that reference in counter (the returned implement function). As long as counter exists, at least one reference to localCounter exists. This seems strange because localCounter is a value type, not a reference type. But that's what "The Swift Programming Language" guide says it does.