iOS Closures in Swift First Class Functions Capturing Variables

Kristof Kocsis
Kristof Kocsis
10,587 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

Michael Psoinos
Michael Psoinos
8,130 Points

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.