#57: Capturing Values in Swift Closures

Closures can capture variables from the surrounding scope and keep using them later.

func makeCounter() -> () -> Int {
    var value = 0
    return {
        value += 1
        return value
    }
}

let counter = makeCounter()
counter() // 1
counter() // 2

Here the closure keeps value alive even after makeCounter() has returned.

This behavior is incredibly useful, but it is also why closures can keep objects alive longer than expected.


I'm also on Twitter and GitHub.

Subscribe via RSS.