Closures Capture Values

Closures and functions can keep track of internal information encapsulated by a variable defined in their enclosing scope. To see an example of this, imagine that Knowhere is booming. As growth can be erratic, you create a function that will allow you to update the town’s population data based on recent growth. Your town planner will update the town’s census data every time the population grows by 500 people.

Listing 13.11  Tracking growth

...
print("Knowhere has \(stoplights) stoplights.")

func makeGrowthTracker(forGrowth growth: Int) -> () -> Int {
    var totalGrowth = 0
    func growthTracker() -> Int {
        totalGrowth += growth
        return totalGrowth
    }
    return growthTracker
}
var currentPopulation = 5422
let growBy500 ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.